public
Last active

sweet.js simple enum macro

  • Download Gist
enum_example.js
JavaScript
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'
// });

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 ]);

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.