/
shuffle.ts
41 lines (37 loc) · 1.08 KB
/
shuffle.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import { purry } from "./purry";
/**
* Shuffles the input array, returning a new array with the same elements in a random order.
*
* @param items - The array to shuffle.
* @signature
* R.shuffle(array)
* @example
* R.shuffle([4, 2, 7, 5]) // => [7, 5, 4, 2]
* @dataFirst
* @category Array
*/
export function shuffle<T>(items: ReadonlyArray<T>): Array<T>;
/**
* Shuffles the input array, returning a new array with the same elements in a random order.
*
* @signature
* R.shuffle()(array)
* @example
* R.pipe([4, 2, 7, 5], R.shuffle()) // => [7, 5, 4, 2]
* @dataLast
* @category Array
*/
export function shuffle<T>(): (items: ReadonlyArray<T>) => Array<T>;
export function shuffle(): unknown {
return purry(_shuffle, arguments);
}
function _shuffle<T>(items: ReadonlyArray<T>): Array<T> {
const result = items.slice();
for (let index = 0; index < items.length; index++) {
const rand = index + Math.floor(Math.random() * (items.length - index));
const value = result[rand]!;
result[rand] = result[index]!;
result[index] = value;
}
return result;
}