Created
October 10, 2018 20:32
-
-
Save carlin-q-scott/e4ff559551952c59a30205540ed54ee8 to your computer and use it in GitHub Desktop.
Attempt at creating an enum using Proxy and Class
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
class Enum extends Proxy { | |
constructor(...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)); | |
super( | |
members, | |
{ | |
get: (target, name) => { | |
if (!members[name]) { | |
throw new Error(`Member '${name}' not found on the Enum.`); | |
} | |
return members[name]; | |
}, | |
set: () => { | |
throw new Error('Adding new members to Enums is not allowed.'); | |
} | |
} | |
); | |
} | |
} | |
export default Enum; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment