Created
June 17, 2013 13:01
-
-
Save nooga/5796689 to your computer and use it in GitHub Desktop.
Silly experiments with "macros" in JS.
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
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