[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
Looking to practice more questions like these? We recommend GreatFrontEnd, the best platform for honing your frontend interview skills!
- Define the
clamp
function with three arguments:number
,lower
, andupper
. - Check if the
number
is less than the lower bound:- If yes, return the lower bound itself.
- Check if the
number
is greater than the upper bound:- If yes, return the upper bound itself.
- 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
- Define the
clamp
function with three arguments:number
,lower
, andupper
. - Use
max(number, lower)
to ensure the number is no less than the lower bound. - Use
min(max_result, upper)
to ensure the number is no greater than the upper bound. - The final result is the number clamped within the desired range.
function clamp(number, lower, upper) {
return Math.min(upper, Math.max(lower, number));
}