Add arrayFlatten (#816)

* Add arrayFlatten

* Add test for arrayFlatten

* Add arrayChunk

* Update packages/util/src/array/chunk.ts
This commit is contained in:
Jaco Greeff
2020-12-23 11:58:59 +01:00
committed by GitHub
parent 5aad1d09b2
commit 7871a17942
6 changed files with 99 additions and 0 deletions
+12
View File
@@ -0,0 +1,12 @@
// Copyright 2017-2020 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { arrayChunk } from '.';
describe('arrayChunk', (): void => {
it('chunks arrays', (): void => {
expect(
arrayChunk([1, 2, 3, 4, 5, 6, 7], 3)
).toEqual([[1, 2, 3], [4, 5, 6], [7]]);
});
});
+29
View File
@@ -0,0 +1,29 @@
// Copyright 2017-2020 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
/**
* @name arrayChunk
* @summary Split T[] into T[][] based on the defind size
* @description
* Returns a set ao arrays based on the chunksize
* @example
* <BR>
*
* ```javascript
* import { arrayChunk } from '@polkadot/util';
*
* arrayChunk([1, 2, 3, 4, 5]); // [[1, 2], [3, 4], [5]]
* ```
*/
export function arrayChunk <T> (array: T[], chunkSize: number): T[][] {
const outputSize = Math.ceil(array.length / chunkSize);
const output = Array<T[]>(outputSize);
for (let index = 0; index < outputSize; index++) {
const offset = index * chunkSize;
output[index] = array.slice(offset, offset + chunkSize);
}
return output;
}
+12
View File
@@ -0,0 +1,12 @@
// Copyright 2017-2020 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { arrayFlatten } from '.';
describe('arrayFlatten', (): void => {
it('flattens arrays', (): void => {
expect(
arrayFlatten([[0], [1, 2, 3], [4, 5], [6], [], [7, 8]])
).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8]);
});
});
+36
View File
@@ -0,0 +1,36 @@
// Copyright 2017-2020 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
// This is supposed to be a faster concat...
// https://dev.to/uilicious/javascript-array-push-is-945x-faster-than-array-concat-1oki
/**
* @name arrayFlatten
* @summary Merge T[][] into T[]
* @description
* Returns a new array with all arrays merged into one
* @example
* <BR>
*
* ```javascript
* import { arrayFlatten } from '@polkadot/util';
*
* arrayFlatten([[1, 2], [3, 4], [5]]); // [1, 2, 3, 4, 5]
* ```
*/
export function arrayFlatten <T> (arrays: T[][]): T[] {
// pre-allocate based on the combined size
const output = new Array<T>(arrays.reduce((length, array) => length + array.length, 0));
let index = -1;
for (let a = 0; a < arrays.length; a++) {
const array = arrays[a];
// instead of pushing, we just set the entries
for (let e = 0; e < array.length; e++) {
output[++index] = array[e];
}
}
return output;
}
+2
View File
@@ -5,4 +5,6 @@
* @summary Utility methods that operates on arrays
*/
export { arrayChunk } from './chunk';
export { arrayFilter } from './filter';
export { arrayFlatten } from './flatten';