This does not want to be a "just-use-a-library" answer but just in case you're using Lodash you can use .clamp
:
_.clamp(yourInput, lowerBound, upperBound);
So that:
_.clamp(22, -10, 10); // => 10
Here is its implementation, taken from Lodash source:
/**
* The base implementation of `_.clamp` which doesn't coerce arguments.
*
* @private
* @param {number} number The number to clamp.
* @param {number} [lower] The lower bound.
* @param {number} upper The upper bound.
* @returns {number} Returns the clamped number.
*/
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;
}
Also, it's worth noting that Lodash makes single methods available as standalone modules, so in case you need only this method, you can install it without the rest of the library:
npm i --save lodash.clamp