From dbeb1ea0004c977c30d29b531088d60f91dfbec0 Mon Sep 17 00:00:00 2001 From: yfwmaniish Date: Sun, 6 Sep 2026 11:25:37 +0530 Subject: [PATCH] fix(array): respect negative step in range() to avoid an infinite loop --- src/array.test.ts | 4 ++++ src/array.ts | 15 +++++++++++---- 2 files changed, 15 insertions(+), 4 deletions(-) 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