Clamp
Prompt
Write a function clamp(value, min, max) that constrains a number within a range. If the number is below the minimum, return the minimum. If it's above the maximum, return the maximum. Otherwise, return the number unchanged.
clamp(10, 0, 5); // 5 (10 is above max, so return 5)
clamp(-10, 0, 5); // 0 (-10 is below min, so return 0)
clamp(3, 0, 5); // 3 (3 is within range, return as is)Playground
There are only three possible cases: the value is too low, too high, or just right. You can handle each with a simple comparison.
JavaScript has Math.min and Math.max built in. You can
combine them to solve this in a single expression without
any if statements.
Solution
Explanation
The clamp function takes three parameters: value (the number we want to constrain), min (the lower boundary), and max (the upper boundary). It makes sure the value never goes below min or above max.
This is one of those small utility functions that you'll reach for all the time. Progress bars use it to keep the percentage between 0 and 100. Drag-and-drop uses it to prevent elements from being dragged outside a container. Slider inputs use it to keep the thumb within bounds. Any time you have a number that shouldn't go outside a range, clamp is your friend.
The solution is a single line, but it does two things:
return Math.min(Math.max(value, min), max);Math.max(value, min) handles the "too low" case. If value is smaller than min, it returns min. Otherwise it returns value. So after this step, we know the result is at least min.
Then Math.min(result, max) handles the "too high" case. If the result from the first step is larger than max, it returns max. Otherwise it keeps the value. So now we know the result is at most max.
- For
clamp(10, 0, 5):Math.max(10, 0)gives10, thenMath.min(10, 5)gives5. - For
clamp(-10, 0, 5):Math.max(-10, 0)gives0, thenMath.min(0, 5)gives0. - For
clamp(3, 0, 5):Math.max(3, 0)gives3, thenMath.min(3, 5)gives3.
Alternative with if-statements
If the Math.min(Math.max(...)) approach doesn't come to mind, a straightforward if-statement version is just as valid:
function clamp(value, min, max) {
if (value < min) return min;
if (value > max) return max;
return value;
}Both produce the same result. The if version is arguably easier to read.
Lodash includes clamp as a built-in utility function. If
your project already uses Lodash, you can use _.clamp()
instead of writing your own.
Resources
Lodash Clamp