Clamp
EasyPrompt
Write a function that takes a number and returns it clamped between a minimum and maximum value. If the number is less than the minimum, return the minimum. If the number is greater than the maximum, return the maximum. Otherwise, return the number as is.
Arguments
value
: The number to clampmin
: The minimum boundarymax
: The maximum boundary
Return Value
- A number that is clamped between the minimum and maximum values
Example
console.log(clamp(10, 0, 5)); // => 5
console.log(clamp(-10, 0, 5)); // => 0
console.log(clamp(3, 0, 5)); // => 3
Playground
First check if the value is less than the minimum. If so, return the minimum.
Next check if the value is greater than the maximum. If so, return the maximum.
If the value is between the minimum and maximum (inclusive), just return the value as is.
Solution
Explanation
The clamp
function is a utility that constrains a value within a defined range. It's incredibly useful in a variety of programming scenarios, from controlling animation boundaries to ensuring input values stay within acceptable ranges.
Let's break down how our implementation works:
At its core, the clamp
function takes three parameters:
value
- The number we want to constrainmin
- The lower boundary of our rangemax
- The upper boundary of our range
Our solution uses a clever combination of JavaScript's built-in Math.min
and Math.max
functions:
function clamp(value, min, max) {
return Math.min(Math.max(value, min), max);
}
This compact one-liner actually works in two steps:
- First,
Math.max(value, min)
ensures that our value isn't below the minimum. Ifvalue
is less thanmin
, it returnsmin
; otherwise, it returnsvalue
. - Then,
Math.min(result_from_step_1, max)
ensures that our value isn't above the maximum. If the result from step 1 is greater thanmax
, it returnsmax
; otherwise, it keeps the result from step 1.
So for each of our test cases:
clamp(10, 0, 5)
: First,Math.max(10, 0)
gives us10
. Then,Math.min(10, 5)
gives us5
.clamp(-10, 0, 5)
: First,Math.max(-10, 0)
gives us0
. Then,Math.min(0, 5)
gives us0
.clamp(3, 0, 5)
: First,Math.max(3, 0)
gives us3
. Then,Math.min(3, 5)
gives us3
.
We could also write this function with if-statements:
function clamp(value, min, max) {
if (value < min) return min;
if (value > max) return max;
return value;
}