Math.clamp method?

Tagir Valeev amaembo at gmail.com
Fri Jan 27 10:49:22 UTC 2023


Hello, Remi!

> Given that the semantics of NaN is clearly defined for Math.max/min (if one of the values is NaN the result is NaN),
> I don't believe we need a special case here for NaN.
>
> The semantics should be, this is equivalent to execute
>   Math.max(min, Math.min(max, value))
>
> So clamp(double) can be implemented using minsd and maxsd on x64, which is already what the VM does.

I agree that for NaN value, it's reasonable to return NaN. However, I
think it's better to throw if min or max is NaN,
as we should check the invariant that min <= max. We can do this in a
single check:
if (!(min <= max)) throw new IllegalArgumentException(...);

With best regards,
Tagir Valeev.


More information about the core-libs-dev mailing list