Last active
December 16, 2015 01:39
-
-
Save snowmantw/5356844 to your computer and use it in GitHub Desktop.
Because using Array is too mainstream
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
// From http://stackoverflow.com/questions/14850511/js-matrix-multiplication-issue | |
function multiplyMatrix(m1, m2) { | |
var result = []; | |
for(var j = 0; j < m2.length; j++) { | |
result[j] = []; | |
for(var k = 0; k < m1[0].length; k++) { | |
var sum = 0; | |
for(var i = 0; i < m1.length; i++) { | |
sum += m1[i][k] * m2[j][i]; | |
} | |
result[j].push(sum); | |
} | |
} | |
return result; | |
} | |
mtx = function(){ | |
var la = arguments.length | |
if(mtx.rows[0] || (mtx.rows[0] ? la == mtx.rows[0].length : true )) | |
{ | |
var row = [] | |
for(var i = 0; i < la; i++) | |
{ | |
row.push(arguments[i]) | |
} | |
mtx.rows.push( row ) | |
} | |
else | |
{ | |
throw "Invalid matrix: different length of rows." | |
} | |
return mtx | |
} | |
mtx.rows = [] | |
mtx.cmds = [] | |
mtx.get = function() | |
{ | |
if( 0 == mtx.cmds.length ){ return mtx.rows} | |
else | |
{ | |
mtx.cmds.forEach(function(cmd, idx) | |
{ | |
var result = cmd(mtx.rows) | |
mtx.rows = result | |
}) | |
return mtx.rows | |
} | |
} | |
mtx.mul = function(){ | |
var m_prev = mtx.rows | |
mtx.rows = [] | |
mtx.cmds. | |
unshift(function(m_curr) | |
{ | |
return multiplyMatrix(m_curr, m_prev) | |
}) | |
// Pass the first row to mtx to storage it. | |
return mtx.apply({}, arguments) | |
} | |
mtx( 1, 2, 3) | |
( 4, 5, 6) | |
( 7, 8, 9) | |
(10,11,12). | |
mul(11,12,13,14) | |
(14,15,16,15) | |
(17,18,19,16). | |
mul( 3) | |
( 4) | |
( 5) | |
( 6). | |
get() | |
/* Last result | |
[ | |
[1716] | |
[4164] | |
[6612] | |
[9060] | |
] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The main idea is to let the function want to implement arbitrary calls return itself, until the next named function got called. And the next function must can be accessed by the current returned function, just like the "return this" trick used in the chaining style.