From 1072eb4200aba15d9caf0e71b6b9134e0ef5ca29 Mon Sep 17 00:00:00 2001 From: draarivpatel-ui <287273626+draarivpatel-ui@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:01:50 -0600 Subject: [PATCH] fix shuffle hanging on empty or invalid ranges 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 #302. --- src/shuffle.js | 4 +++- test/shuffle-test.js | 29 +++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/src/shuffle.js b/src/shuffle.js index 426cdac0..61e8b12f 100644 --- a/src/shuffle.js +++ b/src/shuffle.js @@ -2,7 +2,9 @@ export default shuffler(Math.random); export function shuffler(random) { return function shuffle(array, i0 = 0, i1 = array.length) { - let m = i1 - (i0 = +i0); + i0 = Math.max(0, Math.floor(+i0)); + i1 = Math.max(i0, Math.min(array.length, Math.floor(+i1))); + let m = i1 - i0; while (m) { const i = random() * m-- | 0, t = array[m + i0]; array[m + i0] = array[i + i0]; diff --git a/test/shuffle-test.js b/test/shuffle-test.js index f262d31f..ab185d9d 100644 --- a/test/shuffle-test.js +++ b/test/shuffle-test.js @@ -30,3 +30,32 @@ it("shuffler(random)(array, start, end) shuffles the subset array[start:end] in- assert.strictEqual(shuffle(numbers, 3, 8), numbers); assert.deepStrictEqual(numbers, [0, 1, 2, 5, 6, 3, 4, 7, 8, 9]); }); + +it("shuffler(random)(array, start, end) returns the array unchanged when start > end", () => { + const numbers = [0, 1, 2, 3, 4]; + const shuffle = shuffler(randomLcg(0.9051667019185816)); + assert.strictEqual(shuffle(numbers, 2, 0), numbers); + assert.deepStrictEqual(numbers, [0, 1, 2, 3, 4]); +}); + +it("shuffler(random)(array, start) returns the array unchanged when start is past the end of the array", () => { + const numbers = [0, 1]; + const shuffle = shuffler(randomLcg(0.9051667019185816)); + assert.strictEqual(shuffle(numbers, 3), numbers); + assert.deepStrictEqual(numbers, [0, 1]); +}); + +it("shuffler(random)(array, start, end) shuffles the floored range when the bounds are non-integer", () => { + const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; + const shuffle = shuffler(randomLcg(0.9051667019185816)); + assert.strictEqual(shuffle(numbers, 0.5, 10), numbers); + assert.deepStrictEqual(numbers.slice().sort((a, b) => a - b), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); +}); + +it("shuffler(random)(array, start, end) clamps the range to the array", () => { + const numbers = [0, 1, 2, 3, 4]; + const shuffle = shuffler(randomLcg(0.9051667019185816)); + assert.strictEqual(shuffle(numbers, 0, 20), numbers); + assert.strictEqual(numbers.length, 5); + assert.deepStrictEqual(numbers.slice().sort((a, b) => a - b), [0, 1, 2, 3, 4]); +});