In RangeLoading saved progress…

In Range

Implement inRange(number, start, end) — a boolean membership test that answers "does this number fall inside this range?" The range is half-open: the low bound is included, the high bound is not, so the test is start <= number < end. This mirrors Lodash's _.inRange, including its two convenience behaviors: call it with just two arguments and the second is treated as end (with start defaulting to 0), and pass the bounds in descending order and they are swapped before testing so the range always runs low-to-high.

Signature

// number: number   — the value to test.
// start:  number    — low bound, INCLUSIVE. Defaults to 0 when end is omitted.
// end:    number    — high bound, EXCLUSIVE. If omitted, start is used as end.
// returns: boolean  — true when the (ordered) range contains number.
function inRange(number, start, end): boolean;

Examples

inRange(3, 2, 4); // → true   (2 ≤ 3 < 4)
inRange(4, 4, 8); // → true   (start is inclusive)
inRange(8, 4, 8); // → false  (end is exclusive)
inRange(4, 8);      // → true   two args: range is [0, 8)
inRange(-3, -2, -6); // → true  bounds swap to [-6, -2)
inRange(5, 5, 5);   // → false  a zero-width range contains nothing

Notes

  • Half-open range. start is inclusive and end is exclusive: use <= against the low bound but < against the high bound.
  • Two arguments mean (number, end). When end is omitted, shift it: the second argument becomes end and start defaults to 0.
  • Descending bounds are swapped. If start > end, order them low-to-high before testing — inRange(-3, -2, -6) is the range [-6, -2).
  • Zero-width ranges are empty. When the two bounds are equal there is no value v with start <= v < end, so the answer is always false.
  • Return a boolean. The result is true/false, not the number or a truthy/falsy expression.
Loading editor…