Skip to content

Instantly share code, notes, and snippets.

@gogromat
Last active July 11, 2023 16:31
Show Gist options
  • Save gogromat/446e962bde1122747cfe to your computer and use it in GitHub Desktop.
Save gogromat/446e962bde1122747cfe to your computer and use it in GitHub Desktop.
Concatenate n-many ArrayBuffers
/**
* Concatenates n-many ArrayBuffers
* Based on the https://gist.github.com/72lions/4528834
*
* @param {...ArrayBuffer} ArrayBuffer(s) to concatenate
* @return {ArrayBuffer} The new ArrayBuffer created out of n buffers.
*/
var concatArrayBuffers = function () {
var buffers = Array.prototype.slice.call(arguments),
buffersLengths = buffers.map(function(b) { return b.byteLength; }),
totalBufferlength = buffersLengths.reduce(function(p, c) { return p+c; }, 0),
unit8Arr = new Uint8Array(totalBufferlength);
buffersLengths.reduce(function (p, c, i) {
unit8Arr.set(new Uint8Array(buffers[i]), p);
return p+c;
}, 0);
return unit8Arr.buffer;
};
// To call it:
// concatArrayBuffers.apply(this/context, [ArrayBuffers]);
@jonathan-annett
Copy link

jonathan-annett commented Jul 11, 2023

respectfully, i offer this slight modification, to allow mixed type arrays or buffers to be concatenated on arbritrary byte boundaries

function concatArrayBuffers () {
        var buffers = Array.prototype.slice.call(arguments).map(function(ab){
               if (ab.constructor===ArrayBuffer) return ab;
               return new Uint8Array(ab.buffer.slice(ab.byteOffset,ab.byteLength)).buffer; 
            }),
            buffersLengths = buffers.map(function(b) { return b.byteLength; }),
            totalBufferlength = buffersLengths.reduce(function(p, c) { return p+c; }, 0),
            unit8Arr = new Uint8Array(totalBufferlength);
        buffersLengths.reduce(function (p, c, i) {
            unit8Arr.set(new Uint8Array(buffers[i]), p);
            return p+c;
        }, 0);
        return unit8Arr.buffer;
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment