Skip to content

fix(array): respect negative step in range() to avoid an infinite loop - #57

Open
yfwmaniish wants to merge 1 commit into
antfu:mainfrom
yfwmaniish:fix-range-negative-step
Open

fix(array): respect negative step in range() to avoid an infinite loop#57
yfwmaniish wants to merge 1 commit into
antfu:mainfrom
yfwmaniish:fix-range-negative-step

Conversation

@yfwmaniish

Copy link
Copy Markdown

Bug

Closes #49.

range(start, stop, step) loops forever when step is negative, because the loop condition is hard-coded to the positive direction:

let current = start
while (current < stop) {
  arr.push(current)
  current += step || 1   // step = -1 → current keeps decreasing, always < stop
}
range(1, 5, -1) // 🔁 infinite loop (hangs the process)

Fix

Advance in the step's direction, so a negative step counts down and simply produces an empty array when the direction can't reach stop:

step = step || 1 // keep the historical zero-step fallback of 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)
}

Behavior

call before after
range(1, 5, -1) 🔁 infinite loop []
range(5, 1, -1) 🔁 infinite loop [5, 4, 3, 2]
range(10, 2, -2) 🔁 infinite loop [10, 8, 6, 4]
range(2, 10, 2) [2, 4, 6, 8] [2, 4, 6, 8] (unchanged)
range(5) / range(2, 5) unchanged unchanged

Positive-step and zero-step behavior is unchanged; negative steps now count down (matching the intuitive/Python-like semantics) instead of hanging.

Tests

Extended the range test with the reporter's case and descending ranges. Full suite passes (39 passed), lint clean.

Copilot AI lite review requested due to automatic review settings September 6, 2026 05:53

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

The range function received a positive start and stop with a negative step produced an infinite loop

2 participants