diff --git a/index.js b/index.js index 78b4368..99caa9a 100644 --- a/index.js +++ b/index.js @@ -150,4 +150,12 @@ const typedArrayTypes = new Set([ ]); 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 (is.array(range)) && (x >= Math.min.apply(Math, range)) && (x <= Math.max.apply(Math, range)); +}; + module.exports = is; diff --git a/readme.md b/readme.md index 45ade28..40e5d1b 100644 --- a/readme.md +++ b/readme.md @@ -121,6 +121,13 @@ Returns `true` for instances created by a ES2015 class. ##### .typedArray(value) +##### .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. + +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 357aa55..6f5d6a6 100644 --- a/test.js +++ b/test.js @@ -305,3 +305,16 @@ test('is.typedArray', t => { t.false(m.typedArray([])); t.false(m.typedArray({})); }); + +test('is.inRange', t => { + const x = 3; + + t.true(m.inRange(x, [0, 5])); + t.true(m.inRange(x, [5, 0])); + 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(x, 10)); + t.false(m.inRange(x, 2)); +});