Let's say x
, a
and b
are numbers. I need to cap x
to the bounds of the segment [a, b]
.
I can write Math.max(a, Math.min(x, b))
, but i don't think it's very easy to read. Does anybody has a clever way to write this in a more readable way?
Let's say x
, a
and b
are numbers. I need to cap x
to the bounds of the segment [a, b]
.
I can write Math.max(a, Math.min(x, b))
, but i don't think it's very easy to read. Does anybody has a clever way to write this in a more readable way?
If you don’t want to define any function, writing it like
Math.min(Math.max(x, a), b)
isn’t that bad.Update for ECMAScript 2017:
But note that as of today, it's a Stage 1 proposal. Until it gets widely supported, you can use a polyfill.
In the spirit of arrow sexiness, you could create a micro clamp/constrain/gate/&c. function using rest parameters
Then just pass in three values
That is, again, if by sexy, you mean 'short'
The way you do it is pretty standard. You can define a utility
clamp
function like described here:(Although extending language built-ins is generally frowned upon)
If you are able to use es6 arrow functions, you could also use a partial application approach: