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
5 changes: 4 additions & 1 deletion src/shuffle.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ export default shuffler(Math.random);

export function shuffler(random) {
return function shuffle(array, i0 = 0, i1 = array.length) {
let m = i1 - (i0 = +i0);
i0 = +i0;
i1 = +i1;
if (!Number.isInteger(i0) || !Number.isInteger(i1) || i0 < 0 || i1 > array.length || i1 <= i0) return array;
let m = i1 - i0;
while (m) {
const i = random() * m-- | 0, t = array[m + i0];
array[m + i0] = array[i + i0];
Expand Down
16 changes: 16 additions & 0 deletions test/shuffle-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,19 @@ 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]);
});

for (const [start, end] of [[2, 0], [3, 2], [0.5, 2], [0, 1.5], [-1, 2], [0, 3], [NaN, 2], [0, Infinity], [Infinity, Infinity]]) {
it(`shuffle(array, ${start}, ${end}) leaves an invalid range unchanged`, () => {
const numbers = [0, 1];
const shuffle = shuffler(() => assert.fail("should not consume randomness for an invalid range"));
assert.strictEqual(shuffle(numbers, start, end), numbers);
assert.deepStrictEqual(numbers, [0, 1]);
});
}

it("shuffle(array, start, end) coerces numeric bounds", () => {
const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
const shuffle = shuffler(randomLcg(0.9051667019185816));
assert.strictEqual(shuffle(numbers, "3", "8"), numbers);
assert.deepStrictEqual(numbers, [0, 1, 2, 5, 6, 3, 4, 7, 8, 9]);
});