JavaScriptLesson 16 of 16

Final project: an online store cart

Time to put it all together. The cart of a small store is a class, arrays and their methods, errors, a closure, JSON and an async payment in one program.

Key points

  • Cart keeps items and offers add, total and lines
  • An unknown product throws new Error, and try...catch handles it outside
  • The sum comes from reduce, the receipt lines from map with destructuring
  • The promo code lives in a closure: it works once, the second time there is no discount
  • Payment is a promise with setTimeout, and await waits for the result

Example

// The pieces of the project in one placeconst prices = { mug: 12, cap: 18 };const order = [["mug", 2], ["cap", 1]]; const sum = order.reduce((total, [id, qty]) => total + prices[id] * qty, 0);console.log(`Sum: ${sum}`); function makeLimiter(max) {  let used = 0;  return () => (used < max ? `ok ${++used}` : "limit reached");}const tryCode = makeLimiter(1);console.log(tryCode(), tryCode()); const saved = JSON.stringify({ sum });console.log(saved, JSON.parse(saved).sum === sum);

The example is a warm-up: reduce that destructures each [id, qty] pair, a limiter built on a closure and a check that JSON gives back the same sum.

Task

How to use the editor⌘ Enter or Ctrl Enter runs the code, ⇧ ⌘ Enter checks the task.Tab and Shift Tab indent the line or the selection; Esc, then Tab leaves the editor.The check compares what the program printed with the task; spaces at line ends do not matter.After two failed checks you may open the solution. Your code is kept in this browser.

Finish the cart. add(id, qty) looks the product up in catalog (if it is missing, throw new Error(`Unknown product: ${id}`)) and either raises qty or pushes { id, ...product, qty }; total is the sum of price * qty; lines() returns lines like Mug x3 = 36; makePromo gives a percent discount only once. Output: Unknown product: sofa, Mug x3 = 36, T-shirt x1 = 25, Total: 54.90, Promo again: 61.00, {"items":2,"total":54.9} and Paid 54.90.

Output

What your program prints appears here.