8. Pick the Best Promotion at Checkout
During a sale weekend a store runs several promotions at once, but its policy is one promotion per order. Instead of asking shoppers to choose, checkout automatically applies the one that saves the most. Marketing configures promotions of four types in the admin panel. A promotion that does not apply to the cart saves 0.
Your task:
- promotionDiscount(items, promotion): how much one promotion saves on this cart.
- pickBestPromotion(items, promotions): returns { promotionId, discount } for the best one.
Promotion types:
- { id, type: "percentOffCategory", category, percent }: percent off the total of that category's lines, round(sum x percent / 100), half up.
- { id, type: "buyXGetY", sku, buy, get }: for every complete group of buy + get units of sku, get units are free.
- { id, type: "spendAndSave", tiers: [{ minSubtotal, save }] }: saves the save of the highest tier whose minSubtotal <= cart subtotal. Tiers may be unsorted.
- { id, type: "bundle", skus, bundlePrice }: each complete set (one unit of every sku) costs bundlePrice instead of the sum of the unit prices. The saving is sets x (set price - bundlePrice), or 0 when that is not positive.
Rules:
- items is a list of { sku, category, unitPrice, quantity }, prices in cents.
- Choose the largest discount. Ties go to the promotion listed first.
- When no promotion saves anything, return { promotionId: null, discount: 0 }.
What you'll write
promotionDiscountfunctionThe saving of one promotion on the cart, in cents.pickBestPromotionfunctionThe best promotion for the cart. Uses promotionDiscount.
Each one has its own test cases, and the last one is also tested together with the others. Implement them in order.
Examples
Example 1
- Function
pickBestPromotion- Input
items = [ { sku: "shirt", category: "apparel", unitPrice: 2000, quantity: 3 }, { sku: "jeans", category: "apparel", unitPrice: 4500, quantity: 1 }, { sku: "mug", category: "home", unitPrice: 1200, quantity: 2 } ]promotions = [ { id: "P1", type: "percentOffCategory", category: "apparel", percent: 15 }, { id: "P2", type: "buyXGetY", sku: "shirt", buy: 2, get: 1 }, { id: "P3", type: "spendAndSave", tiers: [ { minSubtotal: 10000, save: 1000 }, { minSubtotal: 20000, save: 3000 } ] } ]
- Output
{ promotionId: "P2", discount: 2000 }
- Explanation
- P1 saves 1575, P2 saves one shirt (2000), P3 saves 1000.
Solution
Write promotionDiscount and pickBestPromotion. Tab indents (Esc then Tab leaves the editor), Ctrl/⌘ + Enter runs. Each run has a 3-second limit. Your code is saved in this browser.
Test Results
Click "Run Code" to test your solution.