gloriaJun / til

Lessoned Learned
3 stars 0 forks source link

Create EnumList in Javascript #64

Open gloriaJun opened 4 years ago

gloriaJun commented 4 years ago

Source Code

class EnumItem {
  constructor(key, obj) {
    if (typeof obj === 'string') {
      this.key = key;
      this.text = obj;
    } else {
      const { key, text, ...values } = obj;
      this.key = key;
      this.text = text;
      Object.keys(values).map(key => {
        this[key] = values[key];
      });
    }

    Object.freeze(this);
  }

  get code() {
    return this.key;
  }

  get display() {
    return this.text;
  }

  equal(key) {
    return this === key || this.key === key;
  }
}

export default class EnumList {
  constructor(enumLiterals) {
    Object.keys(enumLiterals).map(key => {
      this[key] = new EnumItem(key, enumLiterals[key]);
    });

    Object.freeze(this);
  }

  get(key) {
    let values = null;

    if (this[key]) {
      values = this[key];
    } else {
      const findKey = this.keys().find(item => this[item].code === key);
      values = this[findKey];
    }

    return values;
  }

  keys() {
    return Object.keys(this);
  }
}

Usage examples

const ACCOUNT_TYPE = new EnumList({
  SMART_SAVING: 'Smart Saving',
  GOAL_DRIVEN_SAVING: 'Goal driven saving account',
  CREDIT_LOAN: 'Credit loan account',
})

// example
console.log(ACCOUNT_TYPE.SMART_SAVING.value); // SMART_SAVING
console.log(ACCOUNT_TYPE.SMART_SAVING.display); // Smart Saving
console.log(ACCOUNT_TYPE.SMART_SAVING.equal('SMART_SAVING')); // true
console.log(ACCOUNT_TYPE.SMART_SAVING.equal(ACCOUNT_TYPE.SMART_SAVING)); // true