This does not mean that you want to use the answer "just-use-a-library", but if you use Underscore / Lodash, you can use .clamp :
_.clamp(yourInput, lowerBound, upperBound);
So that:
_.clamp(22, -10, 10);
Here is its implementation, taken from Lodash source :
function baseClamp(number, lower, upper) { if (number === number) { if (upper !== undefined) { number = number <= upper ? number : upper; } if (lower !== undefined) { number = number >= lower ? number : lower; } } return number; }
In addition, it is worth noting that Lodash makes individual methods available as stand-alone modules, so if you only need this method, just install it without the rest of the library:
npm i --save lodash.clamp
Nobita Nov 03 '16 at 17:36 2016-11-03 17:36
source share