Reputation: 2520
Is there an easy way to get number between two values or these values? for example:
min: 10, max: 100
(in -> out)
1 -> 10
5 -> 10
10 -> 10
50 -> 50
100 -> 100
1000 -> 100
9999 -> 100
now I'm using this:
Math.max(10, Math.min(100, value));
but is there a more efficient and/or elegant way to do this?
Upvotes: 0
Views: 141
Reputation: 172448
James is right. Check this for detail
/**
* Returns a number whose value is limited to the given range.
*
* Example: limit the output of this computation to between 0 and 255
* (x * 255).clamp(0, 255)
*
* @param {Number} min The lower boundary of the output range
* @param {Number} max The upper boundary of the output range
* @returns A number in the range [min, max]
* @type Number
*/
Number.prototype.clamp = function(min, max) {
return Math.min(Math.max(this, min), max);
};
Upvotes: 0
Reputation: 149020
No, there's really no better way than that. It's probably what I'd go with. If you really want an alternative, you could use the conditional operator like this:
value > 100 ? 100 : value < 10 ? 10 : value;
However, I find this is a lot harder to read than a simple min
/ max
.
Of course, if you find yourself doing this a lot, you can make your own function for brevity:
function clamp(val, min, max) {
return Math.max(min, Math.min(max, val));
}
Then just use it like this:
clamp(value, 10, 100);
Upvotes: 0
Reputation: 14768
This is probably overkill, but here's a reusable solution:
function clamper(min, max) {
return function(v) {
return v > max ? max : (v < min ? min : v);
};
}
var clamp = clamper(0, 100);
console.log(clamp(25));
console.log(clamp(50));
console.log(clamp(74));
console.log(clamp(120));
console.log(clamp(-300));
Fiddle: http://jsfiddle.net/mx3whct6/
Upvotes: 1