0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

JavaScriptで列挙型(Enum)っぽい曜日(DayOfWeek)をSymbolを用いてやってみる

Posted at

そもそもJavaScriptは曜日をなぜか数字で管理しています。(Dateクラス)
全く現代的ではないため、JavaのEnum型DayOfWeekみたいな感じにできたらなと思って書いてみようと思いました。

JavaScriptでEnumを定義する - Qiita
調べてみると、上記記事のコメント欄でSymbolを使うのはどうか?と書かれていました。
Symbolとは文字列引数を用いて唯一な定数を生成するものです。ref: Symbol - JavaScript | MDN

そんな感じで書いてみました。

const DayOfWeek = {
  SUNDAY: Symbol(''), // 0
  MONDAY: Symbol(''), // 1
  TUESDAY: Symbol(''), // 2
  WEDNESDAY: Symbol(''), // 3
  THURSDAY: Symbol(''), // 4
  FRIDAY: Symbol(''), // 5
  SATURDAY: Symbol(''), // 6
};
const DayOfWeeks = {
  values: [
    DayOfWeek.SUNDAY,
    DayOfWeek.MONDAY,
    DayOfWeek.TUESDAY,
    DayOfWeek.WEDNESDAY,
    DayOfWeek.THURSDAY,
    DayOfWeek.FRIDAY,
    DayOfWeek.SATURDAY,
  ],
  getDayOfWeek: index => {
    return DayOfWeeks.values[index];
  },
  getDayOfWeekOfJapaneseChar: char => {
    return DayOfWeeks.values.find(value => value.description == char);
  },
  getDayOfWeekOfJapaneseText: text => {
    return DayOfWeeks.getIndexOfJapaneseChar(text[0]);
  },
  getIndexOf: dayOfWeek => {
    return DayOfWeek.values.indexOf(dayOfWeek);
  },
  getDayOfWeekOfEnglish: text => {
    return DayOfWeek[text];
  },
};
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?