Skip to content

Commit 178846d

Browse files
feat: add array shuffle algorithm
1 parent 5c39e87 commit 178846d

2 files changed

Lines changed: 69 additions & 0 deletions

File tree

‎Data-Structures/Array/Shuffle.js‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/**
2+
* @function shuffle
3+
* @description Randomly shuffles the elements of an array using the
4+
* Fisher-Yates (Knuth) shuffle algorithm.
5+
* @param {Array} arr - The input array to shuffle
6+
* @returns {Array} - A new shuffled array
7+
* @see https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
8+
* @example shuffle([1, 2, 3, 4, 5]) => [3, 1, 5, 2, 4] (random order)
9+
*/
10+
const shuffle = (arr) => {
11+
if (!Array.isArray(arr)) {
12+
throw new TypeError('Input must be an array')
13+
}
14+
const result = [...arr]
15+
for (let i = result.length - 1; i > 0; i--) {
16+
const j = Math.floor(Math.random() * (i + 1))
17+
;[result[i], result[j]] = [result[j], result[i]]
18+
}
19+
return result
20+
}
21+
22+
export { shuffle }
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import { shuffle } from '../Shuffle.js'
2+
3+
describe('shuffle', () => {
4+
test('shuffle returns array of same length', () => {
5+
expect(shuffle([1, 2, 3, 4, 5])).toHaveLength(5)
6+
})
7+
8+
test('shuffle contains all original elements', () => {
9+
const arr = [1, 2, 3, 4, 5]
10+
const result = shuffle(arr)
11+
expect(result.sort()).toEqual([...arr].sort())
12+
})
13+
14+
test('shuffle empty array returns empty array', () => {
15+
expect(shuffle([])).toEqual([])
16+
})
17+
18+
test('shuffle single element returns same array', () => {
19+
expect(shuffle([1])).toEqual([1])
20+
})
21+
22+
test('shuffle does not mutate original array', () => {
23+
const arr = [1, 2, 3, 4, 5]
24+
shuffle(arr)
25+
expect(arr).toEqual([1, 2, 3, 4, 5])
26+
})
27+
28+
test('shuffle works with strings', () => {
29+
const arr = ['a', 'b', 'c', 'd']
30+
const result = shuffle(arr)
31+
expect(result.sort()).toEqual([...arr].sort())
32+
})
33+
34+
test('shuffle returns a new array', () => {
35+
const arr = [1, 2, 3]
36+
const result = shuffle(arr)
37+
expect(result).not.toBe(arr)
38+
})
39+
40+
test('throws TypeError for non-array input', () => {
41+
expect(() => shuffle('123')).toThrow(TypeError)
42+
})
43+
44+
test('throws TypeError for null input', () => {
45+
expect(() => shuffle(null)).toThrow(TypeError)
46+
})
47+
})

0 commit comments

Comments
 (0)