Skip to content

Instantly share code, notes, and snippets.

@ceane
Last active August 29, 2015 14:12
Show Gist options
  • Save ceane/9cf6fba9e2527d8ea0f5 to your computer and use it in GitHub Desktop.
Save ceane/9cf6fba9e2527d8ea0f5 to your computer and use it in GitHub Desktop.

#Magical enums in ES6 My brain exploded with creativity today with this nefarious trick to make an enum by manipulating the syntax in ES6. The browser vendors will probably find this and block this from shipping, but it will still work with a transpiler (webpack + 6to5). To understand this you will need to know ES6 Proxies, ES6 modules, and Symbols.

your-code.js

import { blue, red, orange } from 'magic-enum';

var color = blue;

switch (color) {
  case blue:
    console.log('color is blue!!');
    break;
  case red:
    console.log('color is red!!');
    break;
  case orange:
    console.log('color is orange!');
    break;
}

The small amount of code that makes it happen...

magic-enum.js

var magic = {};
export default new Proxy(magic, {
  get(target, property) {
    return Symbol(property);
  }
})

Of course this means that your enum cannot have initializers (i.e. { blue=1, red, green }).

/**
* This example works in Firefox, the only browser with proxies currently
*/
//Just generates a random string, not an implementation of Symbol
function Symbol(desc) {
var len = 9;
for (var str = ''; str.length < len; str += Math.random().toString(36).substr(2));
return 'Symbol(' + desc + ':' + str.substr(0, len) +')';
}
var magic = {};
var ENUM = new Proxy(magic, {
get: function(target, property) {
return Symbol(property)
}
});
var { red, green, blue } = ENUM;
var { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday } = ENUM;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment