How can I simulate macros in JavaScript?

2019-01-14 02:53发布

问题:

I know that JavaScript doesn't support macros (Lisp-style ones) but I was wondering if anyone had a solution to maybe simulate macros? I Googled it, and one of the solutions suggested using eval(), but as he said, would be quite costly.

They don't really have to be very fancy. I just want to do simple stuff with them. And it shouldn't make debugging significantly harder :)

回答1:

You could use parenscript. That'll give you macros for Javascript.



回答2:

A library by Mozilla (called SweetJS) is designed to simulate macros in JavaScript. For example, you can use SweetJS to replace the function keyword with def.



回答3:

One can also now use ClojureScript to compile clojure to javascript and get macros that way. Note ClojureScript uses Google Closure.



回答4:

I've written a gameboy emulator in javascript and I simulate macros for cpu emulation this way:

macro code (the function returns a string with the macro code):

function CPU_CP_A(R,C) { // this function simulates the CP instruction, 
  return ''+             // sets CPU flags and stores in CCC the number
  'FZ=(RA=='+R+');'+     // of cpu cycles needed
  'FN=1;'+
  'FC=RA<'+R+';'+
  'FH=(RA&0x0F)<('+R+'&0x0F);'+
  'ICC='+C+';';
}

Using the "macro", so the code is generated "on the fly" and we don't need to make function calls to it or write lots of repeated code for each istruction...

OP[0xB8]=new Function(CPU_CP_A('RB',4)); // CP B
OP[0xB9]=new Function(CPU_CP_A('RC',4)); // CP C
OP[0xBA]=new Function(CPU_CP_A('RD',4)); // CP D
OP[0xBB]=new Function(CPU_CP_A('RE',4)); // CP E
OP[0xBC]=new Function('T1=HL>>8;'+CPU_CP_A('T1',4)); // CP H
OP[0xBD]=new Function('T1=HL&0xFF;'+CPU_CP_A('T1',4)); // CP L
OP[0xBE]=new Function('T1=MEM[HL];'+CPU_CP_A('T1',8)); // CP (HL)
OP[0xBF]=new Function(CPU_CP_A('RA',4)); // CP A

Now we can execute emulated code like this:

OP[MEM[PC]](); // MEM is an array of bytes and PC the program counter

Hope it helps...



回答5:

LispyScript is the latest language that compiles to Javascript, that supports macros. It has a Lisp like tree syntax, but also maintains the same Javascript semantics. Disclaimer: I am the author of LispyScript.



回答6:

function unless(condition,body) {
    return 'if(! '+condition.toSource()+'() ) {' + body.toSource()+'(); }';
}


eval(unless( function() {
    return false;
  }, function() {
    alert("OK");
}));


回答7:

Javascript is interpreted. Eval isn't any more costly that anything else in Javascript.