From 83adc096ef2f49bc60727df8dba7638a788f14d6 Mon Sep 17 00:00:00 2001 From: Brandon Smith Date: Thu, 26 Oct 2017 09:30:17 -0400 Subject: [PATCH] Add `is.arrayLike()` (#26) --- index.js | 3 +++ readme.md | 14 ++++++++++++++ test.js | 12 ++++++++++++ 3 files changed, 29 insertions(+) diff --git a/index.js b/index.js index 5c5e656..ed9fed7 100644 --- a/index.js +++ b/index.js @@ -155,6 +155,9 @@ const typedArrayTypes = new Set([ ]); is.typedArray = x => typedArrayTypes.has(getObjectType(x)); +const isValidLength = x => is.safeInteger(x) && x > -1; +is.arrayLike = x => !is.nullOrUndefined(x) && !is.function(x) && isValidLength(x.length); + is.inRange = (x, range) => { if (is.number(range)) { return x >= Math.min(0, range) && x <= Math.max(range, 0); diff --git a/readme.md b/readme.md index a99dd93..20e9441 100644 --- a/readme.md +++ b/readme.md @@ -160,6 +160,20 @@ Returns `true` for instances created by a ES2015 class. ##### .typedArray(value) +##### .arrayLike(value) + +A `value` is array-like if it is not a function and has a `value.length` that is a safe integer greater than or equal to 0. + +```js +is.arrayLike(document.forms); +//=> true + +function () { + is.arrayLike(arguments); + //=> true +} +``` + ##### .inRange(value, range) Check if `value` (number) is in the given `range`. The range is an array of two values, lower bound and upper bound, in no specific order. diff --git a/test.js b/test.js index f35eb08..8b7967c 100644 --- a/test.js +++ b/test.js @@ -392,6 +392,18 @@ test('is.typedArray', t => { t.false(m.typedArray({})); }); +test('is.arrayLike', t => { + (() => { + t.true(m.arrayLike(arguments)); + })(); + t.true(m.arrayLike([])); + t.true(m.arrayLike('unicorn')); + + t.false(m.arrayLike({})); + t.false(m.arrayLike(() => {})); + t.false(m.arrayLike(new Map())); +}); + test('is.inRange', t => { const x = 3;