[Easy] inRange
March 4, 2024
Question Prompt
Imagine you're building a critical system that relies on numerical ranges for data validation. You're tasked with designing and implementing a function called inRange
that plays a crucial role in this validation process.
The function takes three arguments:
value
: The numerical value to be checked.start
(optional): The lower bound of the range (inclusive). Defaults to 0 if not provided.end
: The upper bound of the range (exclusive).
The function's responsibility is to determine whether the value
falls within the specified range, considering these key points:
- Default behavior: If only two arguments are provided, the second argument is treated as
end
, andstart
is set to 0. This allows for simpler usage for common positive ranges. - Negative ranges: If
start
is greater thanend
, the function should intelligently swap the parameters to handle negative ranges correctly. This ensures the function works seamlessly with both positive and negative number lines. - Clear output: The function should return a boolean value (
True
if thevalue
is within the range,False
otherwise).
inRange(3, 2, 4); // => true
inRange(4, 8); // => true
inRange(4, 2); // => false
inRange(2, 2); // => false
inRange(1.2, 2); // => true
Solutions
Looking to practice more questions like these? We recommend GreatFrontEnd, the best platform for honing your frontend interview skills!
The function checks if a value
falls within a range defined by start
and end
. It allows flexibility with optional arguments and negative ranges. And it returns a boolean indicating whether the value
is within the range.
Since end
is optional, we can assign the default value 0 to it using the destructuring assignment (end = 0
). This allows for common positive ranges to be checked easily with only two arguments.
Lastly, check two condition, value >= Math.min(start, end)
ensures the value is greater than or equal to the lower bound, and value < Math.max(start, end)
ensures the value is strictly less than the upper bound (excluding it).
The &&
operator combines these comparisons, returning only if both conditions are met, indicating the value is within the range.
Noted that the end = 0
part plays a key role. It handles the optional nature of the end
argument automatically. Because of it, we can directly check the Math.min
and Math.max
of the start
and end
function inRange(value, start, end = 0) {
return value >= Math.min(start, end) && value < Math.max(start, end);
}