Skip to content

Instantly share code, notes, and snippets.

@snowmantw
Last active December 16, 2015 01:39
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save snowmantw/5356844 to your computer and use it in GitHub Desktop.
Save snowmantw/5356844 to your computer and use it in GitHub Desktop.
Because using Array is too mainstream
// 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]
]
*/
@snowmantw
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment