Skip to main content
πŸ“² JavaScript App Logic

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 same name already exists, add to its quantity. Return the cart (for chaining).
  • removeItem(name) β€” remove a line item by name. Return true if removed, false if not found.
  • applyCoupon(code) β€” apply a discount. Coupons are: "SAVE10" (10% off), "SAVE20" (20% off), "FLAT5" (flat $5 off). Return true if valid, false if unknown.
  • getSubtotal() β€” sum of price Γ— qty for 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.