Skip to content

Fix shuffle hanging on empty or invalid ranges - #304

Open
draarivpatel-ui wants to merge 1 commit into
d3:mainfrom
draarivpatel-ui:fix-shuffle-out-of-range-bounds
Open

draarivpatel-ui wants to merge 1 commit into
d3:mainfrom
draarivpatel-ui:fix-shuffle-out-of-range-bounds

Conversation

@draarivpatel-ui

Copy link
Copy Markdown

Fixes #302.

Problem

shuffle(array, start, end) computes m = i1 - i0 and loops while (m). When the range is empty or invalid, m starts negative (or fractional) and decrements away from zero forever, so the loop never ends. In Node it eventually throws RangeError: Too many properties to enumerate after writing garbage properties at negative/fractional indices.

Reproduction:

shuffle([0, 1, 2, 3, 4], 2, 0); // never returns
shuffle([0, 1], 3);             // never returns
shuffle([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 0.5, 10); // never returns
shuffle([0, 1, 2, 3, 4], 0, 20); // writes past the end

Fix

Normalize the bounds before computing m: floor both to integers, clamp i0 below at 0, and clamp i1 to [i0, array.length]. An empty or invalid range now yields m = 0 and returns the array unchanged, matching the behavior suggested in the issue. Out-of-range ends can no longer write past the array.

Integer in-range bounds are unaffected; all existing tests still pass.

Test

Added four cases to test/shuffle-test.js covering start > end, start past the end of the array, non-integer bounds, and an end past the array length. They timed out / crashed before the fix and pass after. Ran pnpm vitest run test/shuffle-test.js: 8/8 pass.

When start is greater than stop, or the range bounds are non-integer
or out of range, m = i1 - i0 starts negative or fractional and
while (m) never reaches zero, so shuffle loops forever writing
garbage properties. Normalize the bounds with Math.floor and clamp
them to the array so the range is treated as empty instead.

Fixes d3#302.
Copilot AI balanced review requested due to automatic review settings November 24, 2026 20:02

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 insufficient remaining quota. Try requesting a review at a lower effort level.

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

Labels

None yet

Development

Successfully merging this pull request may close these issues.

shuffle hangs forever when start is greater than stop

2 participants