From b30101d07e837797d62bdddb7ae80bf33929fba2 Mon Sep 17 00:00:00 2001 From: glhrmv Date: Mon, 25 Sep 2017 15:07:22 +0100 Subject: [PATCH] Add default 0 as lower bound if range is a number. Update tests --- index.js | 8 +++++++- readme.md | 2 ++ test.js | 10 ++++++++-- 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/index.js b/index.js index 330d91d..0772fa4 100644 --- a/index.js +++ b/index.js @@ -148,6 +148,12 @@ const typedArrayTypes = new Set([ ]); is.typedArray = x => typedArrayTypes.has(getObjectType(x)); -is.inRange = (x, arr) => is.array(arr) && (x >= Math.min.apply(Math, arr)) && (x <= Math.max.apply(Math, arr)); +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 d615e5e..b355b4d 100644 --- a/readme.md +++ b/readme.md @@ -123,6 +123,8 @@ Check to see if the value is within a given range, for example `is.inRange(3, [0 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 ### Why yet another type checking module? diff --git a/test.js b/test.js index 5aa34a5..e3d8b4b 100644 --- a/test.js +++ b/test.js @@ -296,7 +296,13 @@ test('is.typedArray', t => { test('is.inRange', t => { const x = 3; - const arr = [0, 5]; - t.true(m.inRange(x, arr)); + 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)); });