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?
a less "Math" oriented approach ,but should also work , this way, the < / > test is exposed (maybe more understandable than minimaxing) but it really depends on what you mean by "readable"
My favorite:
This does not want to be a "just-use-a-library" answer but just in case you're using Underscore/Lodash you can use
.clamp
:So that:
Here is its implementation, taken from Lodash source:
Also, it's worth noting that Lodash makes single methods available as standalone modules, so in case you need only this method, you can just install it without the rest of the library: