JavaScript | 配列メソッドの使い分け(map / forEach / filter / reduce の違い)

JavaScript JavaScript
スポンサーリンク

では「カート概要を多言語対応(日本語と英語)にする方法」を見てみましょう。


カートの例

const cart = [
  { name: 'Tシャツ', price: 1500, quantity: 2 },
  { name: 'ジーンズ', price: 5000, quantity: 1 },
  { name: '帽子', price: 2000, quantity: 1 }
];
JavaScript

多言語対応の考え方

  • 表示するテキストを テンプレート化 して、言語ごとに切り替える
  • 金額や数量は共通ロジックで計算し、文言だけ差し替える

実装例

function summarizeList(items, max = 3, lang = 'ja') {
  if (items.length === 0) return lang === 'ja' ? '商品はありません' : 'No items';

  if (items.length <= max) {
    return items.join(', ');
  } else {
    const shown = items.slice(0, max).join(', ');
    const remaining = items.length - max;
    return lang === 'ja'
      ? `${shown} …他${remaining}件`
      : `${shown} …and ${remaining} more`;
  }
}

function cartSummary(cart, lang = 'ja', taxRate = 0.1) {
  const validItems = cart.filter(item => item.quantity > 0);

  const names = validItems.map(item => item.name);
  const nameList = summarizeList(names, 3, lang);

  const subtotal = validItems
    .map(item => item.price * item.quantity)
    .reduce((acc, subtotal) => acc + subtotal, 0);

  const totalWithTax = Math.floor(subtotal * (1 + taxRate));
  const itemCount = validItems.reduce((acc, item) => acc + item.quantity, 0);

  if (lang === 'ja') {
    return `カート: ${nameList} / ${itemCount}点 / 合計: ${subtotal.toLocaleString()}円 (税込 ${totalWithTax.toLocaleString()}円)`;
  } else {
    return `Cart: ${nameList} / ${itemCount} items / Subtotal: ¥${subtotal.toLocaleString()} (Tax incl. ¥${totalWithTax.toLocaleString()})`;
  }
}

// 実行
console.log(cartSummary(cart, 'ja'));
// "カート: Tシャツ, ジーンズ, 帽子 / 4点 / 合計: 10,000円 (税込 11,000円)"

console.log(cartSummary(cart, 'en'));
// "Cart: Tシャツ, ジーンズ, 帽子 / 4 items / Subtotal: ¥10,000 (Tax incl. ¥11,000)"
JavaScript

ポイント

  • lang 引数で言語を切り替え
  • summarizeList も言語対応させて「…他◯件」⇔「…and ◯ more」を切り替え
  • 実務ではさらに「i18nライブラリ(例: i18next)」を使うと拡張しやすい

💡 これで「日本語と英語の両対応カート概要」が完成しました。
次のステップとしては、「多言語対応をもっと本格的にする(翻訳辞書を用意して管理する)」方法を見てみると、実務に近づきます。

タイトルとURLをコピーしました