Skip to content

Instantly share code, notes, and snippets.

@benprime
Last active September 30, 2018 17:02
Show Gist options
  • Save benprime/6312531b6bab32afc0373e5602e59219 to your computer and use it in GitHub Desktop.
Save benprime/6312531b6bab32afc0373e5602e59219 to your computer and use it in GitHub Desktop.
const privateStatusEnum = {
UNHARMED: 0,
LIGHTLY_WOUNDED: 1,
MODERATELY_WOUNDED: 2,
SEVERELY_WOUNDED: 3,
INCAPACITATED: 4,
};
const handler = {
get: (obj, prop) => {
if(!(prop in obj)) {
throw new TypeError(`Invalid enum value: ${prop.toString()}`);
}
return obj[prop];
},
set: () => {
throw new TypeError('Cannot set value of enum');
},
};
const StatusEnum = new Proxy(privateStatusEnum, handler);
StatusEnum.UNHARMED; // 0
StatusEnum.UNHARMED = 123; // TypeError: Cannot set value of enum
StatusEnum.BADPROP; // TypeError: Invalid enum value: BADPROP
StatusEnum.BADPROP = 123; // TypeError: Cannot set value of enum
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment