Skip to content

Instantly share code, notes, and snippets.

@jedahu
Created November 13, 2012 10:22
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jedahu/4065056 to your computer and use it in GitHub Desktop.
sweet.js simple enum macro
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
Copy link

yuchi commented Apr 26, 2013

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