arrayShuffle (#1018)

* arrayShuffle

* Update packages/util/src/array/shuffle.spec.ts

* Update packages/util/src/array/shuffle.spec.ts

* Update packages/util/src/array/shuffle.ts

* Early return for length 1
This commit is contained in:
Jaco
2021-06-22 14:54:40 +02:00
committed by GitHub
parent 04a28967c7
commit f437d3aae1
4 changed files with 60 additions and 0 deletions
+7
View File
@@ -1,5 +1,12 @@
# CHANGELOG
## master
Changes:
- Added `arrayShuffle(input)` to shuffle an array into a new output
## 6.9.1 Jun 19, 2021
Changes:
+1
View File
@@ -9,3 +9,4 @@ export { arrayChunk } from './chunk';
export { arrayFilter } from './filter';
export { arrayFlatten } from './flatten';
export { arrayRange } from './range';
export { arrayShuffle } from './shuffle';
+31
View File
@@ -0,0 +1,31 @@
// Copyright 2017-2021 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { arrayRange, arrayShuffle } from '.';
describe('arrayShuffle', (): void => {
it('returns an empty array as-is', (): void => {
expect(
arrayShuffle([])
).toEqual([]);
});
it('returns a single array as-is', (): void => {
expect(
arrayShuffle([100])
).toEqual([100]);
});
it('shuffles an array', (): void => {
const inp = arrayRange(100);
const out = arrayShuffle(inp);
expect(inp).toHaveLength(out.length);
expect(
inp.filter((v) => !out.includes(v))
).toEqual([]);
expect(
JSON.stringify(inp)
).not.toEqual(JSON.stringify(out));
});
});
+21
View File
@@ -0,0 +1,21 @@
// Copyright 2017-2021 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
export function arrayShuffle <T> (input: T[]): T[] {
const result = [...input];
let curr = result.length;
if (curr === 1) {
return result;
}
while (curr !== 0) {
const rand = Math.floor(Math.random() * curr);
curr--;
[result[curr], result[rand]] = [result[rand], result[curr]];
}
return result;
}