LoginSignup
1
0

More than 3 years have passed since last update.

JavascriptでEnumをシンプルに作成

Last updated at Posted at 2020-09-11

仕様

  • 以下のようなオブジェクトリテラルを定義してEnumを作成する。
  • このオブジェクトリテラルにIDをラベルに変換するメソッドを設定するcreate関数を作成。
def.js
const def = {
  OPTION_A: [1, "オプションA"],
  OPTION_B: [2, "オプションB"]
};

利用方法

  • create関数(後段で定義)により仕様を満たすオブジェクトリテラルを作成。
  • 利用は以下のようになる。
use.js

//create関数により仕様を満たすオブジェクトリテラルを作成
const enum = create(def);

console.dir(enum.label(1));
//「オプションA」と表示。

console.dir(enum.OPTION_A)
//「1」と表示

オブジェクトリテラルにIDをラベルに変換するメソッドを設定するcreate関数

  • 定義は以下の通り。
creator.js
const create =  (resource) => {
  //オプションキー、ID、ラベルを格納したオブジェクトリテラルを作成
  const optionSet = {};
  const labels = {};
  for (const [option, idLabel] of Object.entries(resource)) {
    const id = idLabel[0];
    const label = idLabel[1];
    optionSet[option] = id;
    labels[id] = label;
  }
  //IDからラベルを取得する関数を作成
  const getLabel = (labels, id) => {
    return labels[id];
  };
  //オブジェクトリテラルに、IDをラベルに変換する関数を設定
  //bindで冒頭で作ったラベルオブジェクトを設定
  optionSet.label = getLabel.bind(null, labels);
  return optionSet;
}

bindを使って、オブジェクトリテラルに値を保持したメソッドを設定

  • bindを使うことで、「this」を使うようなオブジェクトリテラルを作ることができる。
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0