Created
March 2, 2012 01:37
-
-
Save blendmaster/1954662 to your computer and use it in GitHub Desktop.
Dynamically generating functions with Coffeescript
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
lines = -> Array::join.call arguments, '\n' # joins arguments into a newline separated string | |
# helper function, generates instructions to put base+index into D | |
load_from_base = (base) -> (idx) -> lines "@#{base}", "D=M", "@#{idx}", "A=D+A", "D=M" | |
push_segment = # returns instructions to load value to push into D given index | |
constant: (idx) -> lines "@#{idx}" 'D=A' | |
argument: load_from_base 'ARG' | |
local: load_from_base 'LCL' | |
this: load_from_base 'THIS' | |
that: load_from_base 'THAT' | |
temp: (idx) -> lines '@5', 'D=A', "@#{idx}", 'A=D+A', 'D=M' | |
pointer: (idx) -> lines '@3', 'D=A', "@#{idx}", 'A=D+A', 'D=M' | |
static: (idx) -> lines "@#{filename}.#{idx}", 'D=M' |
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
var lines, load_from_base, push_segment; | |
lines = function(){ | |
return Array.prototype.join.call(arguments, '\n'); | |
}; | |
load_from_base = function(base){ | |
return function(idx){ | |
return lines("@" + base, "D=M", "@" + idx, "A=D+A", "D=M"); | |
}; | |
}; | |
push_segment = { | |
constant: function(idx){ | |
return lines("@" + idx, 'D=A'); | |
}, | |
argument: load_from_base('ARG'), | |
local: load_from_base('LCL'), | |
'this': load_from_base('THIS'), | |
that: load_from_base('THAT'), | |
temp: function(idx){ | |
return lines('@5', 'D=A', "@" + idx, 'A=D+A', 'D=M'); | |
}, | |
pointer: function(idx){ | |
return lines('@3', 'D=A', "@" + idx, 'A=D+A', 'D=M'); | |
}, | |
'static': function(idx){ | |
return lines("@" + filename + "." + idx, 'D=M'); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment