Write a function clamp(value, min, max) that restricts a given number to fall within an inclusive minimum and maximum range. For example, clamp(12, 0, 10) should return 10, clamp(-4, 0, 10) should return 0, and clamp(5, 0, 10) should return 5.
function clamp(value, min, max) {
// your code here
}
Rules:
Must return the value itself if it falls within min and max
Must return min if value is less than min
Must return max if value is greater than max
Assume min is always less than or equal to max
Post your solution as a reply. Answer goes up in about a day.
The clamp function is deceptively simple but incredibly useful for things like animation loops or UI scaling, where you need values to stay within a visual boundary. My solution would handle the comparisons directly:
function clamp(value, min, max) {
if (value < min) {
return min;
}
if (value > max) {
return max;
}
return value;
}
Challenge solution: The challenge asks for a JavaScript function clamp(value, min, max) that restricts a number to a specified range.
One way to do it:
function clamp(value, min, max) {
return Math.max(min, Math.min(value, max));
}
Why:
This solution uses Math.min to first ensure that value does not exceed max. The result of that operation is then passed to Math.max to ensure it is not less than min. This two-step process effectively clamps the value within the desired range.
A simple way is to use Math.min() and Math.max() together:
function clamp(value, min, max) {
return Math.max(min, Math.min(value, max));
}
It keeps the value within the inclusive range. If it’s below min, it returns min; if it’s above max, it returns max. Otherwise, it returns the original value.
@ArthurDent Nice one — I like how readable this is. The two early returns map straight onto the rules, low side then high side, and anything in between just falls through to return value. No clever tricks needed, and it’s the kind of version I’d actually want to come back to later and still understand at a glance.