Foundation project
Project: a shopping cart
Lesson 12 of 20 · 20 min · Module 3: Classes and objects
Build the core of a shopping cart as a class: adding products, changing quantities, applying a discount code, and producing totals that never suffer from floating-point rounding.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Model money safely with integer cents
- Design a class around a private Map
- Expose results through getters and a summary
The idea
Store prices in cents as integers: 0.1 + 0.2 is not exactly 0.3 in JavaScript, but 10 + 20 is exactly 30. Keep the items in a private Map keyed by product id, validate everything before changing it, and format money only when showing it.
console.log(0.1 + 0.2, (10 + 20) / 100);
console.log((1999 / 100).toFixed(2));
01Integers for money
Floating-point numbers cannot represent most decimal fractions exactly, so 0.1 + 0.2 prints 0.30000000000000004. Integer cents add up exactly; divide by 100 only for display.
console.log(0.1 + 0.2 === 0.3, 10 + 20 === 30);false true02Private storage, public behaviour
The Map is #private, so other code cannot put an item with a negative price into it. Every change goes through add or remove, where the rules are checked.
03Derived values are getters
count, subtotal and total are calculated from the items every time. There is no stored total that could drift out of sync after a change.
Your project brief
Cart with:•
add({ id, name, price }, qty = 1): price in cents (positive integer) and qty (positive integer), otherwise throw RangeError; adding an existing id increases its quantity;•
remove(id): throws Error for an unknown id;• a
count getter with the total number of units;•
applyCoupon(code): "SAVE10" gives 10% off the subtotal (rounded down to whole cents), other codes throw Error;• a
total getter in cents after the discount;•
summary(): lines like "2 × Tea — 7.00" in order of adding, then "Total: 12.60".What the checks look for
- Adds items and counts units
- Rejects invalid prices and quantities
- Removes items and refuses unknown ones
- Applies SAVE10, rounding the discount down, and rejects other codes
- Produces a readable summary
Take this with you
Keep money in cents, rules in methods, and totals derived.
Go a little further
Add setQuantity(id, qty), which removes the item when qty is 0, and an "items" getter that returns copies of the stored items.