1
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 3 years have passed since last update.

[JavaScript] よくあるswitch文を書き換える

Last updated at Posted at 2020-08-18

switch文を回避したいなーって時に使えるかもしれない集にしたかったのですが、
よくよく考えてみると、この2パターンくらいしかない気持ちになりました。
これらを応用すれば、大体のswitch文は書き換えられるじゃないかという気がしてます。
因みに、私はswitch文嫌いじゃないです。

ある条件に該当するかどうかを判定する

switch文の場合

function isKanto(prefecture) {
  switch (prefecture) {
    case '茨城県':
    case '栃木県':
    case '群馬県':
    case '埼玉県':
    case '千葉県':
    case '東京都':
    case '神奈川県':
      return true;
    }
  return false;
  }
}

isKanto('群馬県') // => true
isKanto('北海道') // => false

回避した場合

const KANTO = ['茨城県', '栃木県', '群馬県', '埼玉県', '千葉県', '東京都', '神奈川県']

function isKanto(prefecture) {
  return KANTO.includes(prefecture)
}

isKanto('群馬県') // => true
isKanto('北海道') // => false

ある条件から別の値を返す

switch文の場合

function getKenchoushozaichi(prefecture) {
  switch (prefecture) {
    case '北海道':
      return '札幌市';
    case '青森県':
      return '青森市';
    case '岩手県':
      return '盛岡市';
    // ...
    case '沖縄県':
      return '那覇市';
    default:
      return null;
  }
}
getKenchoushozaichi('青森県') // => "青森市"
getKenchoushozaichi('グンマー') // => null

回避した場合

const KENCHOUSHOZAICHI = {
  北海道: '札幌市',
  青森県: '青森市',
  岩手県: '盛岡市',
  // ...
  沖縄県: '那覇市'
};

function getKenchoushozaichi(prefecture) {
  return KENCHOUSHOZAICHI[prefecture] ?? null;
}

getKenchoushozaichi('青森県') // => "青森市"
getKenchoushozaichi('グンマー') // => null
1
0
4

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?