What you're building
A ShoppingCart class that manages line items and applies discount codes at checkout. E-commerce logic is one of the most common real-world JS exercises β and interviewers love asking about rounding and edge cases.
Requirements
addItem(name, price, qty)β add or update a line item. If the samenamealready exists, add to its quantity. Return the cart (for chaining).removeItem(name)β remove a line item by name. Returntrueif removed,falseif not found.applyCoupon(code)β apply a discount. Coupons are:"SAVE10"(10% off),"SAVE20"(20% off),"FLAT5"(flat $5 off). Returntrueif valid,falseif unknown.getSubtotal()β sum ofprice Γ qtyfor all items, rounded to 2 decimal places.getTotal()β subtotal minus any applied discount, never below 0, rounded to 2 decimal places.itemCount()β total quantity of all items in the cart.
Stretch goals
- Support stacking multiple coupons (each applies to the running total).
- Add a
clear()method that empties the cart and removes any coupon.
What this proves
You can model real business rules cleanly: data aggregation, conditional discounts, floating-point rounding β the staples of any payments or e-commerce feature.
β‘ 40 XP
solution.jsRuns in your browser
Loading editorβ¦
Tests4 to pass
addItem accumulates quantity for duplicates
SAVE20 coupon reduces total by 20%
FLAT5 coupon deducts $5 flat
total never goes below zero
Run your code to check these.