diff --git a/src/shuffle.js b/src/shuffle.js index 426cdac..61e8b12 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 f262d31..ab185d9 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]); +});