UNPKG

1.21 kBJavaScriptView Raw
1import { u8aToU8a } from './toU8a.js';
2/**
3 * @name u8aConcat
4 * @summary Creates a concatenated Uint8Array from the inputs.
5 * @description
6 * Concatenates the input arrays into a single `UInt8Array`.
7 * @example
8 * <BR>
9 *
10 * ```javascript
11 * import { { u8aConcat } from '@polkadot/util';
12 *
13 * u8aConcat(
14 * new Uint8Array([1, 2, 3]),
15 * new Uint8Array([4, 5, 6])
16 * ); // [1, 2, 3, 4, 5, 6]
17 * ```
18 */
19export function u8aConcat(...list) {
20 const count = list.length;
21 const u8as = new Array(count);
22 let length = 0;
23 for (let i = 0; i < count; i++) {
24 u8as[i] = u8aToU8a(list[i]);
25 length += u8as[i].length;
26 }
27 return u8aConcatStrict(u8as, length);
28}
29/**
30 * @name u8aConcatStrict
31 * @description A strict version of [[u8aConcat]], accepting only Uint8Array inputs
32 */
33export function u8aConcatStrict(u8as, length = 0) {
34 const count = u8as.length;
35 let offset = 0;
36 if (!length) {
37 for (let i = 0; i < count; i++) {
38 length += u8as[i].length;
39 }
40 }
41 const result = new Uint8Array(length);
42 for (let i = 0; i < count; i++) {
43 result.set(u8as[i], offset);
44 offset += u8as[i].length;
45 }
46 return result;
47}