Last active
June 26, 2021 11:12
-
-
Save jonathanconway/bf7ac2cfd53f69a4e478627370bf8874 to your computer and use it in GitHub Desktop.
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
/** | |
* 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