Created
December 11, 2014 22:17
-
-
Save etlovett/cbda7687a59a4e6bce59 to your computer and use it in GitHub Desktop.
Enum implementation for JS for simple Map-style enums
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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