From bf32335eb96b4d9e162f14d382460ecc35d457b2 Mon Sep 17 00:00:00 2001 From: Kodie Grantham Date: Fri, 6 Oct 2017 15:15:22 -0500 Subject: [PATCH] Clean up is.any() and is.all() code. Throw in some validation --- index.js | 43 ++++++++++++++++++++++++------------------- test.js | 16 ++++++++++++++++ 2 files changed, 40 insertions(+), 19 deletions(-) diff --git a/index.js b/index.js index 9c1c082..32b853f 100644 --- a/index.js +++ b/index.js @@ -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; diff --git a/test.js b/test.js index e2107bb..e69442f 100644 --- a/test.js +++ b/test.js @@ -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); + }); });