diff --git a/src/array.test.ts b/src/array.test.ts index 2d1a218..022f1e3 100644 --- a/src/array.test.ts +++ b/src/array.test.ts @@ -30,6 +30,10 @@ it('range', () => { expect(range(2)).toEqual([0, 1]) expect(range(2, 5)).toEqual([2, 3, 4]) expect(range(2, 10, 2)).toEqual([2, 4, 6, 8]) + // negative step counts down, and never loops forever when the direction is wrong + expect(range(1, 5, -1)).toEqual([]) + expect(range(5, 1, -1)).toEqual([5, 4, 3, 2]) + expect(range(10, 2, -2)).toEqual([10, 8, 6, 4]) }) it('partition', () => { diff --git a/src/array.ts b/src/array.ts index db9f26d..805a1fb 100644 --- a/src/array.ts +++ b/src/array.ts @@ -148,10 +148,17 @@ export function range(...args: any): number[] { } const arr: number[] = [] - let current = start - while (current < stop) { - arr.push(current) - current += step || 1 + // A zero step would never advance; keep the historical fallback of 1. + // Respect the step's direction so a negative step counts down instead of + // looping forever (e.g. `range(1, 5, -1)` is empty, `range(5, 1, -1)` counts down). + step = step || 1 + if (step > 0) { + for (let current = start; current < stop; current += step) + arr.push(current) + } + else { + for (let current = start; current > stop; current += step) + arr.push(current) } return arr