Skip to content
This repository was archived by the owner on Jan 12, 2023. It is now read-only.

Commit 5d258f3

Browse files
author
Kevin Hermawan
committed
refactor: implements Sattolo cycle for shuffle function
1 parent 9afede3 commit 5d258f3

File tree

2 files changed

+6
-4
lines changed

2 files changed

+6
-4
lines changed

Diff for: README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ console.log(result); // [2, 3, 4, 5, 1]
154154
155155
#### [shuffle](/src/shuffle.ts)
156156

157-
Shuffles the element of the array. Implements [Fisher-Yates shuffle Algorithm](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle).
157+
Shuffles the element of the array. Implements [Sattolo cycle](https://rosettacode.org/wiki/Sattolo_cycle).
158158

159159
```ts
160160
import { shuffle } from 'enhanced-array';

Diff for: src/shuffle.ts

+5-3
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
export function shuffle<T>(array: T[]) {
22
const result = array;
33

4-
for (let i = result.length - 1; i > 0; i -= 1) {
5-
const randomIndex = Math.floor(Math.random() * (i + 1));
4+
for (let i = result.length; i > 1; i--) {
5+
const randomIndex = Math.floor(Math.random() * i);
66

7-
result.splice(i, 1, result.splice(randomIndex, 1, result[i])[0]);
7+
const temp = result[i - 1];
8+
result[i - i] = result[randomIndex];
9+
result[randomIndex] = temp;
810
}
911

1012
return result;

0 commit comments

Comments
 (0)