UNPKG

1.22 kBJavaScriptView Raw
1// Copyright 2017-2022 @polkadot/util authors & contributors
2// SPDX-License-Identifier: Apache-2.0
3import { u8aToU8a } from "./toU8a.js";
4/**
5 * @name u8aConcat
6 * @summary Creates a concatenated Uint8Array from the inputs.
7 * @description
8 * Concatenates the input arrays into a single `UInt8Array`.
9 * @example
10 * <BR>
11 *
12 * ```javascript
13 * import { { u8aConcat } from '@polkadot/util';
14 *
15 * u8aConcat(
16 * new Uint8Array([1, 2, 3]),
17 * new Uint8Array([4, 5, 6])
18 * ); // [1, 2, 3, 4, 5, 6]
19 * ```
20 */
21
22export function u8aConcat(...list) {
23 const u8as = new Array(list.length);
24 let length = 0;
25
26 for (let i = 0; i < list.length; i++) {
27 u8as[i] = u8aToU8a(list[i]);
28 length += u8as[i].length;
29 }
30
31 return u8aConcatStrict(u8as, length);
32}
33/**
34 * @name u8aConcatStrict
35 * @description A strict version of [[u8aConcat]], accepting only Uint8Array inputs
36 */
37
38export function u8aConcatStrict(u8as, length = 0) {
39 let offset = 0;
40
41 if (!length) {
42 for (let i = 0; i < u8as.length; i++) {
43 length += u8as[i].length;
44 }
45 }
46
47 const result = new Uint8Array(length);
48
49 for (let i = 0; i < u8as.length; i++) {
50 result.set(u8as[i], offset);
51 offset += u8as[i].length;
52 }
53
54 return result;
55}
\No newline at end of file