Last active
March 7, 2022 23:09
-
-
Save icodeforlove/a4ee3ee9d1546ff212d700d85118d57e to your computer and use it in GitHub Desktop.
Float32Array concatenation uses buffers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}; |
Author
icodeforlove
commented
Jul 14, 2016
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment