Concatenating Typed Arrays

[2015-10-02] esnext, dev, javascript
(Ad, please don’t block)

Typed Arrays don’t have a method concat(), like Arrays do. The work-around is to use the method

typedArray.set(arrayOrTypedArray, offset=0)

That method copies an existing Typed Array (or normal Array) into typedArray at index offset. Then you only have to make sure that typedArray is big enough to hold all (Typed) Arrays you want to concatenate:

function concatenate(resultConstructor, ...arrays) {
    let totalLength = 0;
    for (let arr of arrays) {
        totalLength += arr.length;
    }
    let result = new resultConstructor(totalLength);
    let offset = 0;
    for (let arr of arrays) {
        result.set(arr, offset);
        offset += arr.length;
    }
    return result;
}
console.log(concatenate(Uint8Array,
    Uint8Array.of(1, 2), Uint8Array.of(3, 4)));
        // Uint8Array [1, 2, 3, 4]