Minor tweaks to is.inRange()

This commit is contained in:
Sindre Sorhus 2017-09-26 02:32:58 +07:00
parent 3cbef48b6c
commit 26ca195302
3 changed files with 34 additions and 6 deletions

View file

@ -152,10 +152,15 @@ is.typedArray = x => typedArrayTypes.has(getObjectType(x));
is.inRange = (x, range) => { is.inRange = (x, range) => {
if (is.number(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; module.exports = is;

View file

@ -123,11 +123,22 @@ Returns `true` for instances created by a ES2015 class.
##### .inRange(value, range) ##### .inRange(value, range)
Check to see if the value is within a given range, for example `is.inRange(3, [0, 5])`. 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.
The range supplied can be an array of any size, though this will only check for
the minimum and maximum values in it. ```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 ## FAQ

12
test.js
View file

@ -314,7 +314,19 @@ test('is.inRange', t => {
t.true(m.inRange(x, [-5, 5])); t.true(m.inRange(x, [-5, 5]));
t.true(m.inRange(x, [5, -5])); t.true(m.inRange(x, [5, -5]));
t.false(m.inRange(x, [4, 8])); 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(x, 10));
t.true(m.inRange(0, 0));
t.false(m.inRange(x, 2)); t.false(m.inRange(x, 2));
t.throws(() => {
t.true(m.inRange(0));
});
t.throws(() => {
t.true(m.inRange(0, [5]));
});
}); });