diff --git a/index.js b/index.js index 99caa9a..2ba0ab3 100644 --- a/index.js +++ b/index.js @@ -152,10 +152,15 @@ is.typedArray = x => typedArrayTypes.has(getObjectType(x)); is.inRange = (x, range) => { if (is.number(range)) { - return (x >= Math.min(0, range)) && (x <= Math.max(range, 0)); + return x >= Math.min(0, range) && x <= Math.max(range, 0); } - return (is.array(range)) && (x >= Math.min.apply(Math, range)) && (x <= Math.max.apply(Math, range)); + if (is.array(range) && range.length === 2) { + // TODO: Use spread operator here when targeting Node.js 6 or higher + return x >= Math.min.apply(null, range) && x <= Math.max.apply(null, range); + } + + throw new TypeError('Invalid range'); }; module.exports = is; diff --git a/readme.md b/readme.md index 40e5d1b..6038e65 100644 --- a/readme.md +++ b/readme.md @@ -123,11 +123,22 @@ Returns `true` for instances created by a ES2015 class. ##### .inRange(value, range) -Check to see if the value is within a given range, for example `is.inRange(3, [0, 5])`. -The range supplied can be an array of any size, though this will only check for -the minimum and maximum values in it. +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. + +```js +is.inRange(3, [0, 5]); +is.inRange(3, [5, 0]); +is.inRange(0, [-2, 2]); +``` + +##### .inRange(value, upperBound) + +Check if `value` (number) is in the range of `0` to `upperBound`. + +```js +is.inRange(3, 10); +``` -If `range` is a number (e.g., `is.inRange(3, 10)`), it will be treated as a range of 0 to `range`. ## FAQ diff --git a/test.js b/test.js index 6f5d6a6..18f6158 100644 --- a/test.js +++ b/test.js @@ -314,7 +314,19 @@ test('is.inRange', t => { t.true(m.inRange(x, [-5, 5])); t.true(m.inRange(x, [5, -5])); t.false(m.inRange(x, [4, 8])); + t.true(m.inRange(-7, [-5, -10])); + t.true(m.inRange(-5, [-5, -10])); + t.true(m.inRange(-10, [-5, -10])); t.true(m.inRange(x, 10)); + t.true(m.inRange(0, 0)); t.false(m.inRange(x, 2)); + + t.throws(() => { + t.true(m.inRange(0)); + }); + + t.throws(() => { + t.true(m.inRange(0, [5])); + }); });