Clean up is.any() and is.all() code. Throw in some validation

This commit is contained in:
Kodie Grantham 2017-10-06 15:15:22 -05:00
parent c523b958dc
commit bf32335eb9
2 changed files with 40 additions and 19 deletions

View file

@ -169,30 +169,35 @@ const isEmptyMapOrSet = x => (is.map(x) || is.set(x)) && x.size === 0;
is.empty = x => !x || isEmptyStringOrArray(x) || isEmptyObject(x) || isEmptyMapOrSet(x); is.empty = x => !x || isEmptyStringOrArray(x) || isEmptyObject(x) || isEmptyMapOrSet(x);
is.any = function (predicate, values) { const isAnyOrAll = (all, predicate, values) => {
let ret = false; // `values` is the calling function's "arguments object".
values = Array.prototype.slice.call(arguments, 1); // We have to do it this way to keep node v4 support.
// So here we convert it to an array and slice off the first item.
values = Array.prototype.slice.call(values, 1);
values.forEach(value => { if (is.function(predicate) === false) {
if (predicate(value)) { throw new TypeError(`Invalid predicate: ${util.inspect(predicate)}`);
ret = true; }
}
});
return ret; if (values.length === 0) {
throw new TypeError(`Invalid number of values: ${util.inspect(values.length)}`);
}
if (all) {
return values.every(predicate);
}
return values.some(predicate);
}; };
is.all = function (predicate, values) { // We have to use anonymous functions for the any() and all() methods
let ret = true; // to get the arguments since we can't use rest parameters in node v4.
values = Array.prototype.slice.call(arguments, 1); is.any = function (predicate) {
return isAnyOrAll(false, predicate, arguments);
};
values.forEach(value => { is.all = function (predicate) {
if (!predicate(value)) { return isAnyOrAll(true, predicate, arguments);
ret = false;
}
});
return ret;
}; };
module.exports = is; module.exports = is;

16
test.js
View file

@ -408,6 +408,14 @@ test('is.any', t => {
t.true(m.any(m.object, false, {}, 'unicorns')); t.true(m.any(m.object, false, {}, 'unicorns'));
t.false(m.any(m.boolean, '🦄', [], 3)); t.false(m.any(m.boolean, '🦄', [], 3));
t.false(m.any(m.integer, true, 'lol', {})); t.false(m.any(m.integer, true, 'lol', {}));
t.throws(() => {
m.any(null, true);
});
t.throws(() => {
m.any(m.string);
});
}); });
test('is.all', t => { test('is.all', t => {
@ -415,4 +423,12 @@ test('is.all', t => {
t.true(m.all(m.boolean, true, false)); t.true(m.all(m.boolean, true, false));
t.false(m.all(m.string, '🦄', [])); t.false(m.all(m.string, '🦄', []));
t.false(m.all(m.set, new Map(), {})); t.false(m.all(m.set, new Map(), {}));
t.throws(() => {
m.all(null, true);
});
t.throws(() => {
m.all(m.string);
});
}); });