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?

JavaScriptでMapを使ったSwitchの代替方法

Last updated at Posted at 2025-01-20

はじめに

JavaScriptでは、switch文を使って複数の条件分岐を処理することが一般的ですが、Mapを活用すると、コードをより簡潔で効率的に記述することができます。本記事では、Mapを使ったswitch文の代替方法について解説します。

Mapを使った基本構造

Mapを使用する場合、条件に応じた処理を関数として格納し、キーを使って対応する関数を呼び出す形で動作させます。以下は具体例です。

const operations = new Map([
  ['add', (a, b) => a + b],
  ['subtract', (a, b) => a - b],
  ['multiply', (a, b) => a * b],
  ['divide', (a, b) => a / b]
]);

// 使用例
const operation = 'add'; // 実行したい操作
const a = 10, b = 5;

if (operations.has(operation)) {
  const result = operations.get(operation)(a, b);
  console.log(result); // 出力: 15
} else {
  console.log('無効な操作です');
}

Mapを使うメリット

  1. 簡潔な記述

    • switch文の冗長な記述を避け、コードをシンプルに保てます。
  2. 柔軟なキー

    • Mapでは文字列だけでなく、オブジェクトや関数、NaNなどのキーも使用可能です。
  3. 順序保持

    • Mapではキーの挿入順が保持されるため、順序に依存するロジックも扱いやすくなります。
  4. パフォーマンス

    • 条件が多い場合、大規模なswitch文よりも高速に動作します。
  5. 可読性の向上

    • 各条件ごとの処理を独立した関数として定義することで、コードの見通しが良くなります。

switchとの比較

switch文を使用する場合のコードとMapを使用する場合のコードを比較してみましょう。

switch文の場合

function calculate(operation, a, b) {
  switch (operation) {
    case 'add':
      return a + b;
    case 'subtract':
      return a - b;
    case 'multiply':
      return a * b;
    case 'divide':
      return a / b;
    default:
      throw new Error('無効な操作です');
  }
}

console.log(calculate('add', 10, 5)); // 出力: 15

Mapを使用する場合

const operations = new Map([
  ['add', (a, b) => a + b],
  ['subtract', (a, b) => a - b],
  ['multiply', (a, b) => a * b],
  ['divide', (a, b) => a / b]
]);

const operation = 'add';
const a = 10, b = 5;

console.log(operations.get(operation)(a, b)); // 出力: 15

デフォルト処理の追加

Mapでデフォルト処理を追加する方法も簡単です。例えば、以下のように実装できます。

const operations = new Map([
  ['add', (a, b) => a + b],
  ['subtract', (a, b) => a - b],
  ['multiply', (a, b) => a * b],
  ['divide', (a, b) => a / b]
]);

const operation = 'modulo'; // サポートされていない操作
const a = 10, b = 5;

const result = operations.get(operation) || (() => '無効な操作です');
console.log(result(a, b)); // 出力: "無効な操作です"

まとめ

Mapを使った条件分岐は、switch文の代替として非常に有用です。特に以下のようなケースで効果を発揮します:

  • 条件が多く、可読性を高めたい場合
  • 動的に条件を変更する必要がある場合
  • 高速な処理が求められる場合

ぜひ、Mapを活用して効率的なコードを書いてみてください!

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?