Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a "canonical" name for a function combining min() and max()?

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.

like image 985
Kip Avatar asked Feb 05 '09 15:02

Kip


3 Answers

clamp is a good name.

Let us make it the standard.

like image 166
Niyaz Avatar answered Nov 10 '22 06:11

Niyaz


In some languages you have the function limit

num = limit(val, min, max)

like image 33
Jim C Avatar answered Nov 10 '22 06:11

Jim C


clip(val, lo, hi)
like image 3
jfs Avatar answered Nov 10 '22 07:11

jfs