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.any = function (predicate, values) {
let ret = false;
values = Array.prototype.slice.call(arguments, 1);
const isAnyOrAll = (all, predicate, values) => {
// `values` is the calling function's "arguments object".
// 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 (predicate(value)) {
ret = true;
}
});
if (is.function(predicate) === false) {
throw new TypeError(`Invalid predicate: ${util.inspect(predicate)}`);
}
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) {
let ret = true;
values = Array.prototype.slice.call(arguments, 1);
// We have to use anonymous functions for the any() and all() methods
// to get the arguments since we can't use rest parameters in node v4.
is.any = function (predicate) {
return isAnyOrAll(false, predicate, arguments);
};
values.forEach(value => {
if (!predicate(value)) {
ret = false;
}
});
return ret;
is.all = function (predicate) {
return isAnyOrAll(true, predicate, arguments);
};
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.false(m.any(m.boolean, '🦄', [], 3));
t.false(m.any(m.integer, true, 'lol', {}));
t.throws(() => {
m.any(null, true);
});
t.throws(() => {
m.any(m.string);
});
});
test('is.all', t => {
@ -415,4 +423,12 @@ test('is.all', t => {
t.true(m.all(m.boolean, true, false));
t.false(m.all(m.string, '🦄', []));
t.false(m.all(m.set, new Map(), {}));
t.throws(() => {
m.all(null, true);
});
t.throws(() => {
m.all(m.string);
});
});