I find that I frequently end up writing a function that I always call "clamp()
", that is kind of a combination of min()
and max()
. Is there a standard, "canonical" name for this function?
It always looks something like this:
function clamp($val, $lower, $upper)
{
if ($val < $lower)
return $lower;
else if ($val > $upper)
return $upper;
else
return $val;
}
Or simply using built-in min()
and max()
functions:
function clamp($val, $lower, $upper)
{
return max($lower, min($upper, $val));
}
Variations exist: You can also check for invalid input, where lower > upper
, and either throw an exception or reverse the inputs. Or you can ignore order of the inputs and call it a median-of-three function, but that can be confusing.
clamp is a good name.
Let us make it the standard.
In some languages you have the function limit
num = limit(val, min, max)
clip(val, lo, hi)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With