You can implements macros in Javascript because the compiler is part of the runtime (you can eval
a string and get back code). However to get close to Lisp you need to implement your own full language because eval
can only produce full functions, not expressions.
If instead you're just thinking about delayed evaluation this can be done trivially by wrapping the code in a closure:
function my_if(condition, then_part, else_part) {
return condition ? then_part() : else_part();
}
my_if(foo < bar,
function(){ return bar -= foo; },
function(){ return foo -= bar; });
You can of course also create a closure that will encapsulate the whole operation by delaying also the test...
function my_if(condition, then_part, else_part) {
return function() {
return condition() ? then_part() : else_part();
}
}
var my_prog = my_if(function(){ return foo < bar; },
function(){ return bar -= foo; },
function(){ return foo -= bar; });
my_prog(); // executes the code