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:
@@ -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:
|
||||
|
||||
@@ -9,3 +9,4 @@ export { arrayChunk } from './chunk';
|
||||
export { arrayFilter } from './filter';
|
||||
export { arrayFlatten } from './flatten';
|
||||
export { arrayRange } from './range';
|
||||
export { arrayShuffle } from './shuffle';
|
||||
|
||||
@@ -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));
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
Reference in New Issue
Block a user