Is there a “canonical” name for a function combini

2020-06-30 05:11发布

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.

8条回答
走好不送
2楼-- · 2020-06-30 05:34

In some languages you have the function limit

num = limit(val, min, max)

查看更多
We Are One
3楼-- · 2020-06-30 05:35

I'd just go for a function name "rangeCheck"

查看更多
Evening l夕情丶
4楼-- · 2020-06-30 05:38

What do you think of things like InRangeClosestTo(Number, RangeLowerBound, RangeUpperBound), or ClosestInRange(Number, LowerBoundOfRange, UpperBoundOfRange)? They mean 'Get me the element of the range closest to the number', as I hope is obvious.

The concept is more precise than a Clamp that yeah has two sides but not much more, or a Limit or Bound that might not want to return anything if the number is not within the range,

To me they are clearer then the rest I saw; although it can take a couple of seconds to understand them, you only need to reason about the name, and at most have a brief look at the comment for confirmation; and it's nice when you see how precise it is (it is precise, right?).

You might only have doubts on whether the range is inclusive or not, but I think most people would correctly assume it's inclusive. Alternatively you might use InInclRangeClosestTo and InExclRangeClosestTo, althought I don't see a lot of uses for exclusive ranges.

Of course you should have an auto-completing IDE if you wanted to use them.

查看更多
迷人小祖宗
5楼-- · 2020-06-30 05:41

median

Because it generalizes to more values.

查看更多
\"骚年 ilove
6楼-- · 2020-06-30 05:43

We use pin here. Actually, we use pin for simple ranges and clamp for other stuff.

查看更多
走好不送
7楼-- · 2020-06-30 05:49

clamp is a good name.

Let us make it the standard.

查看更多
登录 后发表回答