UNPKG

530 BJavaScriptView Raw
1/**
2 * @name arrayShuffle
3 * @description Shuffles the input array (unlike sort, this is not done in-place)
4 */
5export function arrayShuffle(input) {
6 const result = input.slice();
7 let curr = result.length;
8 // noop for the single entry
9 if (curr === 1) {
10 return result;
11 }
12 while (curr !== 0) {
13 // ~~ is more performant than Math.floor
14 const rand = ~~(Math.random() * curr);
15 curr--;
16 [result[curr], result[rand]] = [result[rand], result[curr]];
17 }
18 return result;
19}
\No newline at end of file