Ever needed to make sure a value stays within a certain range?
I've often written code like this:
function clamp (value, min, max) {
if (value > maximum) return maximum
if (value < minimum) return minimum
return value
}
let lower = clamp(9, 10, 25) // 10
let higher = clamp(30, 10, 25) // 25
let middle = clamp(22, 10, 25) // 22
Every time I see code like this, I know there's a way to do it with Math.max
and Math.min
but I'm always getting my wires crossed thinking about it.
So here it is:
function clamp (value, min, max) {
return Math.max(min, Math.min(max, value))
}
Next time, I just need to remember "max-min-min-max-value".
Top comments (0)