UNPKG

1.08 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.arrayFlatten = arrayFlatten;
7
8// Copyright 2017-2022 @polkadot/util authors & contributors
9// SPDX-License-Identifier: Apache-2.0
10// This is supposed to be a faster concat...
11// https://dev.to/uilicious/javascript-array-push-is-945x-faster-than-array-concat-1oki
12
13/**
14 * @name arrayFlatten
15 * @summary Merge T[][] into T[]
16 * @description
17 * Returns a new array with all arrays merged into one
18 * @example
19 * <BR>
20 *
21 * ```javascript
22 * import { arrayFlatten } from '@polkadot/util';
23 *
24 * arrayFlatten([[1, 2], [3, 4], [5]]); // [1, 2, 3, 4, 5]
25 * ```
26 */
27function arrayFlatten(arrays) {
28 // pre-allocate based on the combined size
29 let size = 0;
30
31 for (let i = 0; i < arrays.length; i++) {
32 size += arrays[i].length;
33 }
34
35 const output = new Array(size);
36 let i = -1;
37
38 for (let j = 0; j < arrays.length; j++) {
39 const a = arrays[j]; // instead of pushing, we just set the entries
40
41 for (let e = 0; e < a.length; e++) {
42 output[++i] = a[e];
43 }
44 }
45
46 return output;
47}
\No newline at end of file