Skip to content

Instantly share code, notes, and snippets.

@jonathanconway
Last active June 26, 2021 11:12
Show Gist options
  • Save jonathanconway/bf7ac2cfd53f69a4e478627370bf8874 to your computer and use it in GitHub Desktop.
Save jonathanconway/bf7ac2cfd53f69a4e478627370bf8874 to your computer and use it in GitHub Desktop.
/**
* Enum which supports attached methods.
* Each method's `this` is the enum object.
*/
class Enum {
/**
* @param items {Object} Enum keys and values as a plain object
* @param methods {Object} Enum methods as a plain object
* (names are keys, values are methods)
*/
constructor (items, methods) {
Object
.entries(items)
.forEach(([ itemKey, itemValue ]) => {
const itemStr = new String(itemValue);
const boundMethods =
Object.fromEntries(
Object.entries(methods || {})
.map(([ methodKey, methodValue ]) => (
[methodKey, methodValue.bind(itemStr)]
)));
this[itemKey] = Object.assign(itemStr, boundMethods);
});
}
}
const Weekdays = new Enum({
Monday: 'Monday',
Tuesday: 'Tuesday',
Wednesday: 'Wednesday',
Thursday: 'Thursday',
Friday: 'Friday',
Saturday: 'Saturday',
Sunday: 'Sunday'
}, {
abbreviation() {
return this.slice(0, 3);
}
})
console.log(Weekdays.Tuesday.toString()) // "Tuesday"
console.log('Happy ' + Weekdays.Tuesday) // "Happy Tuesday"
console.log(Weekdays.Tuesday.abbreviation()) // "Tue"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment