Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/array.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down
15 changes: 11 additions & 4 deletions src/array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down