Medium
This question is a daily question and will count towards your daily streak.
Your e-commerce platform needs to calculate discounts based on multiple promotions. What total price would a customer pay for their cart using this promotion calculator?
1class PromotionCalculator {2 #promotions = new Map();34 addPromotion(code, calculation) {5 this.#promotions.set(code.toUpperCase(), calculation);6 }78 calculateTotal(basePrice, ...promoCodes) {9 let finalPrice = basePrice;1011 // Sort promo codes to ensure consistent application order12 const sortedCodes = [...new Set(promoCodes)].sort();1314 for (const code of sortedCodes) {15 const promotion = this.#promotions.get(code.toUpperCase());16 if (promotion) {17 finalPrice = promotion(finalPrice);18 }19 }2021 return Number(finalPrice.toFixed(2));22 }23}2425const calculator = new PromotionCalculator();2627// 10% off28calculator.addPromotion('SAVE10', price => price * 0.9);2930// Fixed $20 off31calculator.addPromotion('MINUS20', price => Math.max(0, price - 20));3233// Additional 5% off34calculator.addPromotion('EXTRA5', price => price * 0.95);3536const cartPrice = 100;37console.log(calculator.calculateTotal(38 cartPrice,39 'SAVE10',40 'MINUS20',41 'EXTRA5'42));