Problem overview
A shop keeps its orders in a cart. The lesson builds two classes that work together:
LineItemis one row of the cart: a product name, a price and a quantity. Its constructor takes(name, price, quantity)and stores them inthis.name,this.priceandthis.quantity. Its methodsubtotal()returnsthis.price * this.quantity.Cartholds many rows in a private field#items, which starts as an empty array.add(item)appends aLineItem, andtotal()returns the sum of all the subtotals.
An empty cart totals 0, and the total is worked out each time it is asked for, from the items the cart holds at that moment. The driver creates an empty cart, checks one subtotal, then fills a cart with an apple (5 each, quantity 3), bread (20, quantity 3) and later milk (10, quantity 2). It prints:
Empty: 0
Subtotal: 15
Total: 75
Total: 95
The apple row is 15 and the bread row is 60, so the first total is 75. Adding milk contributes 20 more, giving 95.
Approach: composition and reduce
The two classes have a "has a" relationship: a cart has line items, it isn't one. This is called composition. Cart doesn't need to know how a row computes its own cost. It only asks each row for its subtotal(), and the row answers. If rows later gain discounts, only LineItem changes.
For the total, the cart needs one number from a list of rows. The array method reduce does that. It walks the array carrying a running value: it starts at an initial value, and for each element it replaces the running value with whatever the callback returns. Here the start is 0, and each step adds one row's subtotal.
The alternative is a for loop with a sum variable. It gives the same result, but the lesson uses reduce because summing is exactly what it is for.
Step by step
- Declare
LineItem. - Write its constructor with the three parameters
name,priceandquantity. - Store each value on
this. Withoutthis., the values would vanish when the constructor ends. Three assignments make a row remember all three. - Write
subtotal(). It returns the price times the quantity of this row. Both numbers live onthis. - Declare
CartbelowLineItem. - Declare the private field
#itemsand start it as an empty array. - Write
add(item). It pushes the item ontothis.#items, so the rows stay in the order they were added. - Write
total(). It returns thereduceoverthis.#itemswith a callback that addsit.subtotal()to the running sums, and0as the starting value.
The solution in JavaScript
class LineItem {
constructor(name, price, quantity) {
this.name = name;
this.price = price;
this.quantity = quantity;
}
subtotal() {
return this.price * this.quantity;
}
}
class Cart {
#items = [];
add(item) {
this.#items.push(item);
}
total() {
return this.#items.reduce((s, it) => s + it.subtotal(), 0);
}
}
let empty = new Cart();
console.log("Empty: " + empty.total());
let apple = new LineItem("Apple", 5, 3);
console.log("Subtotal: " + apple.subtotal());
let cart = new Cart();
cart.add(apple);
cart.add(new LineItem("Bread", 20, 3));
console.log("Total: " + cart.total());
cart.add(new LineItem("Milk", 10, 2));
console.log("Total: " + cart.total());
The details a learner might trip on:
- The second argument of
reducematters. The0is the starting value. Without it,reducewould use the first row as the starting value, and adding a subtotal to aLineItemobject builds a string: with the apple and bread rows the result is"[object Object]60", not a number. And on an empty array,reducewith no starting value throwsTypeError: Reduce of empty array with no initial value. With the0, an empty cart simply returns0. - Reading the callback.
(s, it) => s + it.subtotal()takes the running sumsand the current elementit, and returns the new sum. An arrow function with an expression body returns that expression automatically. - Rows are shared, not copied.
addstores the very object it receives. In the driver, the sameappleis used for the subtotal check and then added to the cart. If a row'squantitychanges later, the cart's next total changes with it. For a row of 4 at quantity 2, the total is 8, and after setting the quantity to 5 it becomes 20. - Each cart has its own list. The field initialiser
#items = [];runs for eachnew Cart(), so two carts never share rows. - Private means private.
cart.itemsfrom outside isundefined, andcart.#itemsis a syntax error. The only ways in areaddandtotal.
Complexity
Time: add is O(1). total is O(n) for n rows, because it asks every row for its subtotal each time. That is the cost of working the total out on demand instead of keeping a stored total. The benefit is that the answer can never be out of date.
Space: the cart stores n references, so O(n). total uses only the running sum.
Edge cases and common mistakes
- Leaving out the
0inreduce. The empty cart would throw instead of printingEmpty: 0. - Forgetting
this.in the constructor.price = price;assigns a parameter to itself and leaves the row without a price, sosubtotal()returnsNaN. - Forgetting
returnintotalorsubtotal. The method returnsundefined, and the output readsTotal: undefined. - Zero quantity. A row such as
new LineItem("Pen", 3, 0)has a subtotal of 0 and leaves the total unchanged. - Keeping a running total in a field. If you update it in
addand a row changes later, the stored number goes stale. Recomputing intotal()avoids that. - Decimal prices. Floating-point arithmetic is inexact: a price of
0.1with quantity 3 gives0.30000000000000004. The lesson's driver uses whole numbers, which stay exact. - Strings as numbers.
*converts numeric strings, sonew LineItem("X", 5, "3").subtotal()is 15, but+would join strings. Pass real numbers.
Testing
- An empty
Cart:total()returns0. new LineItem("Apple", 5, 3).subtotal()returns15.- A cart with the apple and bread rows returns
75; after adding milk it returns95. - A cart holding one row,
new LineItem("Pen", 3, 0), returns0.
