Skip to content

Instantly share code, notes, and snippets.

@icodeforlove
Last active March 7, 2022 23:09
Show Gist options
  • Save icodeforlove/a4ee3ee9d1546ff212d700d85118d57e to your computer and use it in GitHub Desktop.
Save icodeforlove/a4ee3ee9d1546ff212d700d85118d57e to your computer and use it in GitHub Desktop.
Float32Array concatenation uses buffers
Float32Array.prototype.concat = function() {
var bytesPerIndex = 4,
buffers = Array.prototype.slice.call(arguments);
// add self
buffers.unshift(this);
buffers = buffers.map(function (item) {
if (item instanceof Float32Array) {
return item.buffer;
} else if (item instanceof ArrayBuffer) {
if (item.byteLength / bytesPerIndex % 1 !== 0) {
throw new Error('One of the ArrayBuffers is not from a Float32Array');
}
return item;
} else {
throw new Error('You can only concat Float32Array, or ArrayBuffers');
}
});
var concatenatedByteLength = buffers
.map(function (a) {return a.byteLength;})
.reduce(function (a,b) {return a + b;}, 0);
var concatenatedArray = new Float32Array(concatenatedByteLength / bytesPerIndex);
var offset = 0;
buffers.forEach(function (buffer, index) {
concatenatedArray.set(new Float32Array(buffer), offset);
offset += buffer.byteLength / bytesPerIndex;
});
return concatenatedArray;
};
@icodeforlove
Copy link
Author

var array1 = new Float32Array(10000000),
    array2 = new Float32Array(10000000);

var array3 = array1.concat(array2);

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