Created
June 22, 2011 21:16
-
-
Save gliese1337/1041237 to your computer and use it in GitHub Desktop.
Map a 2D array onto an underlying contiguous 1D array.
This file contains 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
Matrix = (function(){ | |
function id(){return this;} | |
function _set(idx,src){this[idx]=src;} | |
function _get(idx){return this[idx];} | |
Array.prototype.subarray = function(start,end){ | |
var j,row = {}; | |
for(j=0;start<end;j++,start++){ | |
Object.defineProperty(row,j,{ | |
set:_set.bind(this,start), | |
get:_get.bind(this,start) | |
}); | |
} | |
return row; | |
}; | |
return function(array,r,c){ | |
var i,offset,j,buffer,len; | |
if(!c){ | |
c = r; | |
r = array; | |
array = Int32Array; | |
} | |
len = c*r; | |
buffer = (typeof array === 'function')? | |
new array(len):array; | |
if(len > buffer.length && !(buffer instanceof Array)){ | |
throw new Error("Matrix doesn't fit in given array."); | |
} | |
for(offset=i=0;i<r;i++,offset+=c){ | |
this.__defineGetter__(i,id.bind(buffer.subarray(offset,offset+c))); | |
} | |
this.length = len; | |
this.rows = r; | |
this.cols = c; | |
this.array = buffer; | |
return this; | |
} | |
}()); | |
/* | |
//Construct a matrix referencing a Typed Array | |
new Matrix(5,5); //defaults to Int32 | |
new Matrix(Uint8Array,5,5); | |
new Matrix(new Uint8Array(25),5,5); | |
//throw an error | |
try{ | |
new Matrix(new Uint8Array(20),5,5); | |
}catch(e){console.log(e);} | |
//Map a matrix onto a flat JS array | |
new Matrix([1,2,3,4,5,6,7],5,5); | |
new Matrix(Array,5,5); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment