inRange
Prompt
Write a function inRange(value, start, end) that returns true if value falls within the range (inclusive of both boundaries), and false otherwise. The function should work correctly even if start is greater than end.
Playground
What if someone calls inRange(7, 10, 5) where start is
bigger than end? You might need to swap them first so that
start is always the lower number.
Once you know start is the smaller number, the check is just: is value >= start AND value <= end?
Solution
Explanation
The core logic is just one line: value >= start && value <= end. If value is at least as big as start and at most as big as end, it's in range.
The only tricky part is handling the case where someone passes start bigger than end (like inRange(7, 10, 5)). If we didn't handle this, the check 7 >= 10 && 7 <= 5 would return false even though 7 is clearly between 5 and 10.
We fix this by swapping them first:
if (start > end) {
[start, end] = [end, start];
}This is array destructuring used for swapping. [start, end] = [end, start] swaps the two values in one line without needing a temporary variable. After the swap, start is always the smaller number and end is always the larger, regardless of the order they were passed in.
This same function exists in Lodash as _.inRange(), though Lodash's version treats the end as exclusive by default.