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: 3 additions & 1 deletion src/shuffle.js
Original file line number Diff line number Diff line change
Expand Up @@ -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];
Expand Down
29 changes: 29 additions & 0 deletions test/shuffle-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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]);
});