Skip to content

@jedahu /enum_example.js
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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

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.