Last active
February 11, 2022 04:43
-
-
Save AndresSepar/5ed0b325ddf6bb93e3fd7c43ddd2f858 to your computer and use it in GitHub Desktop.
Javascript (ES6) Enum
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
export class Enum { | |
isObject (o) { | |
return (!!o) && (o.constructor === Object); | |
} | |
isArray (a) { | |
return (!!a) && (a.constructor === Array); | |
} | |
flipObject (o) { | |
return Object.entries(o).reduce((obj, [key, value]) => ({ ...obj, [value]: key }), {}) | |
} | |
constructor (keys) { | |
if (!this.isArray(keys) && this.isObject(keys)) { | |
keys = this.flipObject(keys) | |
} | |
for (const [key, value] of Object.entries(keys)) { | |
this[value] = key; | |
} | |
Object.freeze(this); | |
} | |
*[Symbol.iterator]() { | |
for (let key of Object.keys(this)) yield key; | |
} | |
getKeys () { | |
return Object.keys(this) | |
} | |
getValues () { | |
return Object.values(this) | |
} | |
getKey (key) { | |
return this.flipObject(this)[key] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How to use with Array notation
How to use with Object notation