UNPKG

1.1 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.arrayFlatten = void 0;
4/**
5 * @name arrayFlatten
6 * @summary Merge T[][] into T[]
7 * @description
8 * Returns a new array with all arrays merged into one
9 * @example
10 * <BR>
11 *
12 * ```javascript
13 * import { arrayFlatten } from '@polkadot/util';
14 *
15 * arrayFlatten([[1, 2], [3, 4], [5]]); // [1, 2, 3, 4, 5]
16 * ```
17 */
18function arrayFlatten(arrays) {
19 const num = arrays.length;
20 // shortcuts for the empty & single-entry case
21 if (num === 0) {
22 return [];
23 }
24 else if (num === 1) {
25 return arrays[0];
26 }
27 // pre-allocate based on the combined size
28 let size = 0;
29 for (let i = 0; i < num; i++) {
30 size += arrays[i].length;
31 }
32 const output = new Array(size);
33 let i = -1;
34 for (let j = 0; j < num; j++) {
35 const a = arrays[j];
36 // instead of pushing, we just set the entries
37 for (let e = 0, count = a.length; e < count; e++) {
38 output[++i] = a[e];
39 }
40 }
41 return output;
42}
43exports.arrayFlatten = arrayFlatten;