by STRML · 6y ago · 0 comments
function clamp(num, min, max) {
return Math.max(min, Math.min(num, max));
}
That is, if you don't try to do anything fancy and make any parameters optional. Lodash does and it makes the implementation much more complex. _.clamp(input: number, lower?: number, upper: number): number;
https://github.com/lodash/lodash/blob/ddfd9b11a0126db2302cb7... function clamp(num, min, max) {
if (num > max)
return max;
if (num < min)
return min;
return num;
}In lodash's case it might even be all of the above, although I can't speak for the intentions of the authors since there are no comments to guide readers through the process.
Note GP's link points to what looks like the v3 branch. Check out the latest implementation of clamp, with a few less if statements, and what looks like a NaN check using strict equality if you want your mind blown. https://github.com/lodash/lodash/blob/86a852fe763935bb64c125...
clamp(null) returns 0
clamp(undefined) returns NaN
clamp(1, NaN, NaN) returns 0
clamp(1) returns 0
clamp(1, 5, NaN) returns 5
JavaScript is hard to write safe code for.
int clamp(num, min, max)
{
return num switch
{
_ when num > max => max,
_ when num < min => min,
_ => num
};
}
Or as a lambda: Func<int, int, int, int> clamp = (num, min, max) => num switch {_ when num > max => max, _ when num < min => min,_ => num};