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

Commit b76c2c5

Browse files
author
Kevin Hermawan
committed
feat: adds shuffle
1 parent 24b494b commit b76c2c5

File tree

3 files changed

+37
-0
lines changed

3 files changed

+37
-0
lines changed

README.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,21 @@ console.log(result); // [2, 3, 4, 5, 1]
152152
>
153153
> O(n), where n is the length of the array.
154154
155+
#### [shuffle](/src/shuffle.ts)
156+
157+
Shuffles the element of the array. Implements [Fisher-Yates shuffle Algorithm](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle).
158+
159+
```ts
160+
import { shuffle } from 'enhanced-array';
161+
162+
const result = shuffle([1, 2, 3, 4, 5]);
163+
console.log(result); // [5, 3, 2, 4, 1] (shuffled)
164+
```
165+
166+
> **Time complexity:**
167+
>
168+
> O(n), where n is the length of the array.
169+
155170
#### [swap](/src/swap.ts)
156171

157172
Exchanges the element at the specified indices of the array.

src/shuffle.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
export function shuffle<T>(array: T[]) {
2+
const result = array;
3+
4+
for (let i = result.length - 1; i > 0; i -= 1) {
5+
const randomIndex = Math.floor(Math.random() * (i + 1));
6+
7+
result.splice(i, 1, result.splice(randomIndex, 1, result[i])[0]);
8+
}
9+
10+
return result;
11+
}

test/shuffle.test.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { describe, expect, it } from 'vitest';
2+
3+
import { shuffle } from '../src/shuffle';
4+
5+
describe('shuffle', () => {
6+
it('shuffles element correctly', () => {
7+
const result = shuffle([1, 2, 3, 4, 5]);
8+
9+
expect(result).to.not.eql([1, 2, 3, 4, 5]);
10+
});
11+
});

0 commit comments

Comments
 (0)