Skip to content

Instantly share code, notes, and snippets.

@also
Created April 10, 2011 01:37
Show Gist options
  • Save also/911959 to your computer and use it in GitHub Desktop.
Save also/911959 to your computer and use it in GitHub Desktop.
Fix TypedArray.subarray in WebKit and Mozilla
(function () {
var typedArrays = [Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array];
if (window.Float64Array) {
typedArrays.push(Float64Array);
}
// fix for webkit pre slice rename
// https://bugs.webkit.org/show_bug.cgi?id=53618
if (!Float32Array.prototype.subarray) {
typedArrays.forEach(function (cls) {
cls.prototype.subarray = cls.prototype.slice;
});
}
// fix for incorrect offset on subarrays of subarrays
// https://bugzilla.mozilla.org/show_bug.cgi?id=637643
else if (new Int8Array([0, 1, 0]).subarray(1).subarray(1)[0]) {
function subarray (begin, end) {
if (arguments.length === 0) {
// duplicate the array
return new this.constructor(this.buffer, this.byteOffset, this.length);
}
else {
if (begin < 0) {
// relative to end
begin += this.length;
}
// clamp to 0, length
begin = Math.max(0, Math.min(this.length, begin));
if (arguments.length < 2) {
// slice to end
end = this.length;
}
else {
if (end < 0) {
// relative to end
end += this.length;
}
// clamp to begin, length
end = Math.max(begin, Math.min(this.length, end));
}
var byteOffset = this.byteOffset + begin * this.BYTES_PER_ELEMENT;
return new this.constructor(this.buffer, byteOffset, end - begin);
}
}
typedArrays.forEach(function (cls) {
cls.prototype.subarray = subarray;
});
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment