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")}`;
}