Created
June 21, 2016 04:36
-
-
Save jmar777/d151d7112059a1716aa1ecba699fe6fc to your computer and use it in GitHub Desktop.
Enum Implementation using ES6 Proxies and Symbols
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
function Enum(names) { | |
let members = Object.create(null); | |
members.tryParse = name => { | |
if (!members[name]) { | |
throw new Error(`Unable to parse '${name}' as an Enum member.`); | |
} | |
return members[name]; | |
}; | |
names.forEach(name => members[name] = Symbol(name)); | |
return new Proxy(members, { | |
get: (target, name) => { | |
if (!members[name]) { | |
throw new Error(`Member '${name}' not found on the Enum.`); | |
} | |
return members[name]; | |
}, | |
set: (target, name, value) => { | |
throw new Error('Adding new members to Enums is not allowed.'); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@jzaefferer I like that! Mine was a bit of a quick hack for a specific use-case, but obviously doesn't factor in, e.g., serializability (looking back, I can't even remember why I went with
Symbol
values, vs. assigning a more traditional ordinal value). Thanks for sharing the improvements.