clamp(a,b,c)
One way of writing this is: clamp(x,min,max) { return x < min ? min : x > max ? max : x; }
and this is a fine way to do it, but sometimes people forget the order of the arguments, so they feel the need to invent an IDE to help them remember.Another way is writing:
clamp(min,x,max) { return x < min ? min : x > max ? max : x; }
which has the advantage of "visually" putting the unknown between two values. That can help people remember which argument goes where.Yet another way is:
clamp(min,max,x) { return x < min ? min : x > max ? max : x; }
That one is popular amongst ML, Haskell, F# etc, programmers because they have partial application. They write something like: let clampVolume = clamp 0 11
and pat themselves on the back because now they have a function for clamping volumes.Another reason this one is popular is because the last expression is likely to be the biggest expression. That might pay dividends on keeping bugs out.
Something I'd like people to consider is simply taking the middle value.
function clamp(a,b,c) { return [].slice.call(arguments,0).sort()[1] }
function clamp($a,$b,$c){ $x=func_get_args();sort($x);return $x[1]; }
clamp(A,B,C) -> lists:nth(2, lists:sort([A,B,C])).
sub clamp { @_ = sort @_; $_[1] }
clamp:{*x@&1=<x:(x;y;z)};
clamp:{asc[(x;y;z)]1}
This supports any crazy rationale you might have for a particular order, and it is resistant to a lot of bugs you're likely to make since the code isn't particularly repetitive no matter what language you use. Oh and it doesn't have any comparison operators either.The only real downside is that it's slow.
Oh well.
Before we go and fix the compilers to recognise these contortions as a "clamp" function and optimise for it, maybe it's still worth meditating on next time you have a bunch of conditions in your code.