Skip to content

Commit

Permalink
fix(shuffle): Ensure shuffle function does not modify original array (#…
Browse files Browse the repository at this point in the history
…29)

* fix: Ensure shuffle function does not modify original array

* Apply suggestions from code review

---------

Co-authored-by: Sojin Park <raon0211@gmail.com>
  • Loading branch information
kangju2000 and raon0211 authored Jun 8, 2024
1 parent fa22ab1 commit 958de0f
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
8 changes: 8 additions & 0 deletions src/array/shuffle.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,12 @@ describe('shuffle', () => {

expect(shuffle(arr).slice().sort()).toEqual(arr.slice().sort());
});

it('does not modify the original array', () => {
const arr = [1, 2, 3, 4, 5];
const copiedArr = arr.slice();

shuffle(arr);
expect(arr).toEqual(copiedArr);
});
});
9 changes: 5 additions & 4 deletions src/array/shuffle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,15 @@
* // shuffledArray will be a new array with elements of array in random order, e.g., [3, 1, 4, 5, 2]
*/
export function shuffle<T>(arr: T[]): T[] {
const result = arr.slice();

/**
* https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm
*/
for (let i = arr.length - 1; i >= 1; i--) {
for (let i = result.length - 1; i >= 1; i--) {
const j = Math.floor(Math.random() * (i + 1));

[arr[i], arr[j]] = [arr[j], arr[i]];
[result[i], result[j]] = [result[j], result[i]];
}

return arr;
return result;
}

0 comments on commit 958de0f

Please sign in to comment.