Problem overview
A shop keeps its orders in a cart. The lesson asks for two classes that work together:
LineItemis one row of the cart: a productname, apriceand aquantity. Itssubtotal()method returnsprice * quantity.Cartholds many rows in a private array.add(item)appends a row andtotal()returns the sum of all subtotals.
The cart has line items, it is not one. This relationship is called composition: one object keeps other objects as part of its state and uses their methods. Cart doesn't know how a subtotal is worked out, it asks each LineItem.
The driver creates an empty cart and prints its total, which is 0. It creates an apple row (price 5, quantity 3) and prints its subtotal, 15. Then it puts the apple and a bread row (price 20, quantity 3) into a cart and prints the total, 75, adds milk (price 10, quantity 2) and prints 95 as the total.
Approach: each row knows its subtotal, the cart adds them up
Splitting the job gives each class one responsibility. A LineItem knows one multiplication. A Cart knows how to collect rows and how to sum a list. Neither needs to know how the other does its part.
The statement requires that total() is computed every time it is called, from the rows the cart holds at that moment, instead of being stored in a field and updated by add. That way there is no second number that could drift out of step with the rows. Adding an item changes the next total automatically.
To sum the subtotals, the lesson uses the array's reduce. It walks the rows and carries a running sum. The sum starts at 0, and for each row it becomes the old sum plus that row's subtotal. Starting at 0 is also what makes an empty cart total 0.
Step by step
- Declare
LineItemand write its closing brace at once. - Declare three fields:
name: string,price: numberandquantity: number. TypeScript needs every field and its type declared in the class body before the constructor can assign it. - Add the constructor with the same three values as parameters:
nameas a string,priceandquantityas numbers. - Store each parameter in its field with
this.name = name;and the matching lines for price and quantity. Withoutthis.the assignment would only touch the parameter, and the value would vanish when the constructor ends. - Add
subtotal()returning anumber:this.price * this.quantity. - Declare
CartbelowLineItem, with its closing brace. - Declare the field
private items: LineItem[] = [];. The type says "an array ofLineItem", the initializer gives each cart its own empty array, andprivatemeans that only the cart's methods can use it. - Add
add(item: LineItem): voidand push the item ontothis.items. The array keeps the rows in the order they came in. - Add
total(): numberand returnthis.items.reduce(...)with a callback that addsit.subtotal()to the running sums, and with0as the start value.
The solution in TypeScript
class LineItem {
name: string;
price: number;
quantity: number;
constructor(name: string, price: number, quantity: number) {
this.name = name;
this.price = price;
this.quantity = quantity;
}
subtotal(): number {
return this.price * this.quantity;
}
}
class Cart {
private items: LineItem[] = [];
add(item: LineItem): void {
this.items.push(item);
}
total(): number {
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());
It prints:
Empty: 0
Subtotal: 15
Total: 75
Total: 95
TypeScript details worth knowing
- How
reduceruns. For the cart with apple and bread, the sum starts at 0. The first row adds 15 and the second adds 60, sototal()returns 75. After milk is added, the third row adds 20 and the next call returns 95. - The callback's types. The compiler infers that
itis aLineItem, becausethis.itemsis aLineItem[], and thatsis anumber, because the start value is0. That is whyit.subtotal()is checked without any annotation on the callback. - Rows are shared, not copied.
addstores the object that was passed in. In the driver,applegoes into the cart and is still the same object. If you then writeapple.quantity = 4, the cart's nexttotal()is 100 instead of 95, because the total is computed from the rows' current values. - Public against private. The
LineItemfields have no modifier, so they are public.itemsinCartisprivate: usingcart.itemsoutside the class gets a compiler error, while the methodsaddandtotalare the intended way in. - Field initializers.
= []runs once for each newCart, so two carts never share a list. - Numbers are doubles. The driver uses whole-number prices, so the sums are exact. With a price of
0.1and a quantity of 3,subtotal()returns0.30000000000000004.
Complexity
Time. subtotal() and add() are O(1) (array push is amortized O(1)). total() visits each of the n rows once, so it is O(n). Because it is recomputed on each call, asking for the total many times repeats that work, which is the price of never having a stale value.
Space. The cart stores one reference per row, which is O(n). reduce itself needs only the running sum.
Edge cases and common mistakes
- Leaving out the start value.
reducewithout the0uses the first row as the starting sum, so the first row itself, aLineItem, would be added to a number. On an empty array,reducewith no start value throws aTypeError:Reduce of empty array with no initial value. With0, an empty cart returns 0. - Adding prices instead of subtotals. Summing
it.priceignores the quantities. The apple row would count 5 instead of 15. - Storing the total in a field. If
addupdated atotalfield, anything that changes a row later, such as a new quantity, would leave it out of date. - Forgetting
this.in the constructor.price = price;assigns a parameter to itself and the field staysundefined. - Adding the same row twice. Calling
cart.add(apple)twice stores one object in two positions, so the cart counts it twice: for a cart holding only these two entries the total is 30. - Mixing up the two classes.
total()belongs toCart,subtotal()toLineItem. A cart is not a line item, so it doesn't extend it.
Testing
- An empty cart:
total()is 0. new LineItem("Apple", 5, 3).subtotal()is 15.- A cart with the apple row and
new LineItem("Bread", 20, 3):total()is 75. - After adding
new LineItem("Milk", 10, 2)to the same cart:total()is 95. - The apple row alone in a cart:
total()is 15.
