Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

sweet.js simple enum macro

View enum_example.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
macro $enum {
case $name:ident {$val:ident (,) ...} => {
var $name = {$($val: null) (,) ...};
for (var k in $name) {
$name[k] = k;
}
Object.freeze($name);
}
}
 
// Once sweet.js has syntax-case the for-loop
// will be unnecessary.
 
$enum Suites { CLUBS, SPADES, HEARTS, DIAMONDS }
 
// Equivalent to:
//
// var Suites = Object.freeze(
// { CLUBS: 'CLUBS'
// , SPADES: 'SPADES'
// , HEARTS: 'HEARTS'
// , DIAMONDS: 'DIAMONDS'
// });
yuchi commented

A "better" ident to string implementation could be the following:

macro to_string {
  case $x => { (JSON.stringify({ $x: 0 }).slice(2, -4)) }
}

macro enum {
  case [ $val:ident (,) ... ] => {
      (function () {
        var e = {
            $( $val : (to_string $val) ) (,) ...
        };
        Object.freeze(e);
        return e;
    })()
  }
}

console.dir(enum [ Hallo, World ]);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.