3

I'd like to create a macro in sweet.js that allows the user to write for loops in javascript using something akin to the index notation used in tensor calculus. If I supply it with something like:

tensor foo[i][j] = baz[j] + bar[i];

sweet.js will expand it to:

var i, j, li, lj;
for(i=0, li=bar.length; i<li; ++i){
    for(j=0, lj=baz.length; j<lj; ++j){
        foo[i][j] = baz[j] + bar[i];
    }
}

I have a working copy that does not make use of the li and lj variables, i.e. it checks whether i<bar.length and j<baz.length. This has performance implications for large arrays and I'd like to move away from that.

The problem is that I need to create the li and lj variables. I want to take the i and j tokens and concatenate an "l" to them to make a new token. I can't find a way to concatenate tokens in sweet.js as I would, for instance, in the cpp preprocessor using the ## operator. I do understand sweet.js tries to be hygenic unlike the cpp preprocessor, so I'm not sure if this omission was intended. Am I missing something? Is this a restriction imposed by sweet.js? If it is, is there a workaround?

I am using the latest version of sweet.js, version 2.0. This is the same version used by their online editor

16807
  • 1,418
  • 2
  • 18
  • 32

0 Answers0