logo hsb.horse
← Back to snippets index

Snippets

Merging Uint8Arrays

A TypeScript function to merge multiple Uint8Arrays into one. Useful for combining binary data.

Published: Updated:

When working with binary data, there are times you want to combine multiple Uint8Arrays into one. For example, when reassembling chunks received from a split file upload.

Code

function mergeU8Array(...arrays: Uint8Array[]): Uint8Array {
const total = arrays.reduce((acc, cur) => acc + cur.byteLength, 0);
let offset = 0;
return arrays.reduce<Uint8Array>((acc, cur) => {
acc.set(cur, offset);
offset += cur.byteLength;
return acc;
}, new Uint8Array(total));
}

Usage Examples

Merging Multiple Arrays

const part1 = new Uint8Array([1, 2, 3]);
const part2 = new Uint8Array([4, 5, 6]);
const part3 = new Uint8Array([7, 8, 9]);
const merged = mergeU8Array(part1, part2, part3);
// Uint8Array(9) [1, 2, 3, 4, 5, 6, 7, 8, 9]

Handles Empty Arrays

const merged = mergeU8Array(new Uint8Array(), part1);
// Empty arrays are ignored during merge

Implementation Details

  1. First, calculate the total byte length of all arrays using reduce
  2. Allocate a new Uint8Array of that size
  3. Write each array sequentially using the set method
  4. Manage position by advancing the offset

Although we’re performing side effects inside reduce, we use the set method which avoids byte-level copying, making this a relatively efficient implementation.