Skip to content

Instantly share code, notes, and snippets.

@blendmaster
Created March 2, 2012 01:37
Show Gist options
  • Save blendmaster/1954662 to your computer and use it in GitHub Desktop.
Save blendmaster/1954662 to your computer and use it in GitHub Desktop.
Dynamically generating functions with Coffeescript
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'
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