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

后端 未结 8 2085
孤街浪徒
孤街浪徒 2021-02-18 13:03

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 t

相关标签:
8条回答
  • 2021-02-18 13:35

    In some languages you have the function limit

    num = limit(val, min, max)

    0 讨论(0)
  • 2021-02-18 13:37

    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.

    0 讨论(0)
  • 2021-02-18 13:44

    clamp is a good name.

    Let us make it the standard.

    0 讨论(0)
  • 2021-02-18 13:47
    clip(val, lo, hi)
    
    0 讨论(0)
  • 2021-02-18 13:47

    What about bound?

    bound(min, val, max)
    

    Or constrain?

    constrain(val, min, max)
    
    0 讨论(0)
  • 2021-02-18 13:53

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

    0 讨论(0)
提交回复
热议问题