Clamp

Easy

Prompt

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 clamp
  • min: The minimum boundary
  • max: 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

Hint 1

First check if the value is less than the minimum. If so, return the minimum.

Hint 2

Next check if the value is greater than the maximum. If so, return the maximum.

Hint 3

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:

  1. value - The number we want to constrain
  2. min - The lower boundary of our range
  3. max - 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:

  1. First, Math.max(value, min) ensures that our value isn't below the minimum. If value is less than min, it returns min; otherwise, it returns value.
  2. 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 than max, it returns max; 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 us 10. Then, Math.min(10, 5) gives us 5.
  • clamp(-10, 0, 5): First, Math.max(-10, 0) gives us 0. Then, Math.min(0, 5) gives us 0.
  • clamp(3, 0, 5): First, Math.max(3, 0) gives us 3. Then, Math.min(3, 5) gives us 3.

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;
}

Resources

Lodash Clamp
00:00