Skip to content

Instantly share code, notes, and snippets.

@mohayonao
Created August 25, 2011 01:15
Show Gist options
  • Save mohayonao/1169727 to your computer and use it in GitHub Desktop.
Save mohayonao/1169727 to your computer and use it in GitHub Desktop.
Fake TypedArray
function setupTypedArray(name) {
var fake_typedarray;
if (name in window) {
return window[name];
}
console.warn(name + ' is not defined, so use fake.');
fake_typedarray = function(arg) {
var i;
if (typeof arg === 'number' && arg > 0) {
arg >>= 0;
this.length = arg;
while (arg--) {
this[arg] = 0;
}
} else if (arg instanceof Array) {
for (i = arg.length; i--;) {
this[i] = arg[i];
}
this.length = arg.length;
} else {
this.length = 0;
}
};
fake_typedarray.prototype.set = function(array, offset) {
var i, j, jmax;
offset = (offset || 0) >> 0;
for (i = offset, j = 0, jmax = array.length; j < jmax; i++, j++) {
this[i] = array[j];
}
};
fake_typedarray.prototype.subarray = function(begin, end) {
var i, j, result = new fake_typedarray();
if (begin < end) {
for (i = 0, j = begin; j < end; i++, j++) {
result[i] = this[j];
}
result.length = end - begin;
}
return result;
};
return fake_typedarray;
}
var Float32Array = setupTypedArray("Float32Array");
var f0 = new Float32Array(3); // 0 0 0 x x
var f1 = new Float32Array([10, 20]); // 10 20 x x x
var f2 = new Float32Array(5); f2.set(f1, 2); // 0 0 10 20 0
var f3 = f2.subarray(2, 5); // 10 20 0 x x
console.log('f0=', f0[0], f0[1], f0[2], f0[3], f0[4]);
console.log('f1=', f1[0], f1[1], f1[2], f1[3], f1[4]);
console.log('f2=', f2[0], f2[1], f2[2], f2[3], f2[4]);
console.log('f3=', f3[0], f3[1], f3[2], f3[3], f3[4]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment