Skip to content

Instantly share code, notes, and snippets.

@AndresSepar
Last active February 11, 2022 04:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndresSepar/5ed0b325ddf6bb93e3fd7c43ddd2f858 to your computer and use it in GitHub Desktop.
Save AndresSepar/5ed0b325ddf6bb93e3fd7c43ddd2f858 to your computer and use it in GitHub Desktop.
Javascript (ES6) Enum
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]
}
}
@AndresSepar
Copy link
Author

How to use with Array notation

const days = new Enum([
  'monday',
  'tuesday',
  'wednesday',
  'thursday',
  'friday',
  'saturday',
  'sunday'
]);

console.log(days);
/* {monday: 0, tuesday: 1, wednesday: 2, thursday: 3, friday: 4, saturday: 5, sunday: 6} */

console.log([...days]);
/* ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"] */

How to use with Object notation

const sizes = new Enum({
  xsmall: 'xs',
  small: 'sm',
  medium: 'md',
  large: 'lg'
})

console.log(sizes);
/* { large: "lg", medium: "md", small: "sm", xsmall: "xs"} */

console.log(sizes.small);
/* "sm" */

console.log(sizes.getKey(sizes.small));
/* "small" */

console.log([...sizes]);
/* ["xsmall", "small", "medium", "large"] */

console.log(sizes.getKeys());
/* ["xsmall", "small", "medium", "large"] */

console.log(sizes.getValues());
/* ["xs", "sm", "md", "lg"] */

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment