では、消費税や割引を自動計算してくれるバージョンのショッピングカート関数を作ります。
例題:消費税・割引対応カート関数
// 商品オブジェクトを受け取り、消費税・割引も計算する関数
function calculateCart(userName, discount = 0, ...items) {
console.log("購入者:", userName);
// 各商品の名前と価格を表示
items.forEach(item => {
console.log(`商品: ${item.name}, 価格: ${item.price}円`);
});
// 商品合計
const subtotal = items.reduce((acc, item) => acc + item.price, 0);
console.log("小計:", subtotal, "円");
// 割引計算
const afterDiscount = subtotal - discount;
console.log("割引後:", afterDiscount, "円");
// 消費税計算(10%)
const tax = Math.floor(afterDiscount * 0.1);
console.log("消費税 (10%):", tax, "円");
// 合計
const total = afterDiscount + tax;
console.log("合計金額:", total, "円");
return total;
}
// 使用例
calculateCart(
"太郎",
50, // 割引50円
{ name: "りんご", price: 120 },
{ name: "バナナ", price: 80 },
{ name: "オレンジ", price: 150 }
);
/* 出力:
購入者: 太郎
商品: りんご, 価格: 120円
商品: バナナ, 価格: 80円
商品: オレンジ, 価格: 150円
小計: 350 円
割引後: 300 円
消費税 (10%): 30 円
合計金額: 330 円
*/
JavaScript解説
userName- 最初の引数は購入者名
discount = 0- 割引額の引数を追加
- デフォルト値 0 を設定して、割引なしの場合も対応
...items- 残りの引数を商品オブジェクトとしてまとめて配列に
- 合計計算
reduceで小計を計算- 割引を引き、消費税 10% を計算
- 柔軟性
- 商品の数が増えても対応可能
- 割引額も可変で渡せる
- 実務のカート計算に近い設計
💡 ポイント
- restパラメータを使うと、可変長の複雑データ(商品オブジェクト)もまとめて扱える
- 引数の途中にデフォルト値(割引)を挟むことで、より実務寄りの関数設計が可能
reduceや配列操作と組み合わせると、集計処理が非常に簡単になる


