Skip to content

Instantly share code, notes, and snippets.

@etlovett
Created December 11, 2014 22:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save etlovett/cbda7687a59a4e6bce59 to your computer and use it in GitHub Desktop.
Save etlovett/cbda7687a59a4e6bce59 to your computer and use it in GitHub Desktop.
Enum implementation for JS for simple Map-style enums
// ES5 (with underscore.js)
function Enum(obj){
return Object.freeze(_.extend(Object.create(null), obj));
}
// ES6
function Enum(obj){
let target = Object.freeze(Object.assign(Object.create(null), obj));
return new Proxy(target, {
get(target, propKey, receiver){
if (!(propKey in target)){
throw new ReferenceError('Unknown property: ' + propKey);
}
return Reflect.get(target, propKey, receiver);
}
});
}
const MY_ENUM = Enum({
VALUE_A: 'a',
VALUE_B: 'b',
VALUE_C: 'c'
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment