[Easy] clamp

January 26, 2024

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee

Question Prompt

You're working on a system that processes numeric data. Write a function called clamp that takes a number number, a minimum value lower, and a maximum value upper. This function should ensure that the output number always falls within the specified range, including the minimum and maximum values themselves. How would you approach designing and implementing this function?

// In the bound, return as-is.
clamp(7, 0, 9); // => 7

// Smaller than the lower bound, return the lower bound.
clamp(-12, -4, 5); // => -4

// Larger than the upper bound, return the uppder bound.
clamp(18, 3, 9); // => 9

Solutions

  1. Define the clamp function with three arguments: numberlower, and upper.
  2. Check if the number is less than the lower bound:
    • If yes, return the lower bound itself.
  3. Check if the number is greater than the upper bound:
    • If yes, return the upper bound itself.
  4. Otherwise, the number is already within the range, so return the number itself.
function clamp(number, lower, upper) {
  if (number < lower) {
    return lower;
  } else if (number > upper) {
    return upper;
  } else {
    return number;
  }
}

Or we can make the code more concise

  1. Define the clamp function with three arguments: numberlower, and upper.
  2. Use max(number, lower) to ensure the number is no less than the lower bound.
  3. Use min(max_result, upper) to ensure the number is no greater than the upper bound.
  4. The final result is the number clamped within the desired range.
function clamp(number, lower, upper) {
  return Math.min(upper, Math.max(lower, number));
}
☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee