Search code examples
language-agnosticstandardsnomenclature

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.


Solution

  • clamp is a good name.

    Let us make it the standard.