Enums

by incutonez

JavaScript 1.7

function makeEnum(cls, values) {
  values.forEach((value) => {
    let item;
    if (typeof value === 'string') {
      item = new Enum({
        key: value
      });
    }
    cls[item.key] = item;
  })
  return cls;
}

class Enum {
  key = '';
  value = '';
  display = '';

  constructor({
    key,
    value,
    display
  }) {
    this.key = key;
    this.value = value;
    this.display = display ?? key.split(/(?=[A-Z])/).join(' ');
  }

  toString() {
    return this.key;
  }
}

const Colors = makeEnum({}, ['Red', 'Blue', 'BlueGreenOlga'])
console.log(Colors);