Sikau

Project: A JavaScript app · Day 2 · about 40 min

A cart class and a closure

Private fields, getters, chaining, errors — and order numbers from a closure.

Keep the cart honest

A cart is state plus rules: no unknown items, quantities merge, totals always add up. A class with a private field keeps the rules in one place — nobody can reach in and break them. And a closure gives every till its own order counter.

Cart and order numbers

class Cart {
  #lines = [];

  add(id, qty = 1) {
    if (!findItem(id)) throw new Error(`No such item: ${id}`);
    const line = this.#lines.find((l) => l.id === id);
    if (line) line.qty += qty;
    else this.#lines.push({ id, qty });
    return this;
  }

  remove(id) {
    this.#lines = this.#lines.filter((l) => l.id !== id);
    return this;
  }

  clear() {
    this.#lines = [];
    return this;
  }

  get count() {
    return this.#lines.reduce((n, l) => n + l.qty, 0);
  }

  total() {
    return orderTotal(this.#lines);
  }

  lines() {
    return this.#lines.map((l) => ({ ...l }));
  }
}

function makeOrderNumbers(prefix) {
  let n = 0;
  return () => `${prefix}-${String(++n).padStart(3, "0")}`;
}

The rest of this lesson

  • Invariants: rules that always holdexplain
  • A counter that belongs to each tillexplain
  • Who sees the field?predict
  • Merging linespredict
  • Build the cartwrite code
  • Badge quizquiz
  • What you builtrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 6 lessons of Project: A JavaScript app