1 | // Copyright 2017-2022 @polkadot/util authors & contributors
|
2 | // SPDX-License-Identifier: Apache-2.0
|
3 |
|
4 | /**
|
5 | * @name arrayShuffle
|
6 | * @description Shuffles the input array (unlike sort, this is not done in-place)
|
7 | */
|
8 | export function arrayShuffle(input) {
|
9 | const result = input.slice();
|
10 | let curr = result.length; // noop for the single entry
|
11 |
|
12 | if (curr === 1) {
|
13 | return result;
|
14 | }
|
15 |
|
16 | while (curr !== 0) {
|
17 | // ~~ is more performant than Math.floor
|
18 | const rand = ~~(Math.random() * curr);
|
19 | curr--;
|
20 | [result[curr], result[rand]] = [result[rand], result[curr]];
|
21 | }
|
22 |
|
23 | return result;
|
24 | } |
\ | No newline at end of file |