I would be a little upset if a clamp function could throw a validation error when I passed only numbers. I’ve always written clamp to work even if min is larger than max. Basically, clamp comes down to sorting the three numbers and returning the middle one. I’ve never thought of that as an edge case, it just seems like a more general way to think of the operation that gives you less surprises since every possible input has a well-defined output.
back
2 comments
> clamp comes down to sorting the three numbers and returning the middle one
That is a really weird definition of clamp. I would expect to consistently get either min, max, or an error.
I bet Rust doesn't use your weird idea... Yep. Fully sane implementation:
It’s not a definition, it’s an implementation. A definition would be something like ”constrain a number to an interval defined by two other numbers”. That happens to be identical to sorting and picking the middle value. The only difference vs OP’s clamp is that it gives a consistent and predictable result for ”inverted” intervals where min > max, instead of arbitrarily deciding how to collapse the interval.
It is a definition. You've defined the behaviour when min>max and you've chosen a weird way to define it.
That's clever, but it's not a common perspective so the behavior you propose might be quite surprising indeed. And moreover it only applies to this one particular function. The general principle still applies in general.