Skip to content

Instantly share code, notes, and snippets.

@nooga
Created June 17, 2013 13:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nooga/5796689 to your computer and use it in GitHub Desktop.
Save nooga/5796689 to your computer and use it in GitHub Desktop.
Silly experiments with "macros" in JS.
function macro(mfun) {
var fstr = mfun.toString(),
params = fstr
.match(/^function\s*\((.*)\)/)[1]
.replace(/\s+/,'').split(','),
msrc = fstr.match(/^function\s*\(.*\)\s*\{((?:.|\n)*)\}\s*$/)[1];
console.log(fstr, params, msrc);
return function() {
var src = msrc;
for(var i = 0; i < params.length; i++)
src = src.replace(params[i], arguments[i]);
return new Function(src);
};
}
var calc = macro(function(formula){
var x = 1;
for(var i = 0; i < 10; i++) {
x = formula;
console.log("X = ", x, "formula");
}
});
calc("i * 2")();
calc("x + i/2")();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment