A shop keeps its orders in a cart. Build two classes that work together: a LineItem is one row of the cart (a product, its price and how many were bought), and a Cart holds many rows and adds them up. The cart has line items (composition), it is not one.
LineItem
- Typed public fields
name: string,price: number,quantity: number. constructor(name: string, price: number, quantity: number)stores the three values in the fields.subtotal(): numberreturnsthis.price * this.quantity.
Cart
- It keeps its items in
private items: LineItem[] = [](privatemeans only the class's own methods can use it). add(item: LineItem): voidpushes aLineItemonto the array.total(): numberreturns the sum of the subtotals of all items, usingreducewith start value0, so an empty cart gives0.
Rules:
- The total is worked out every time it is asked for, from the items in the cart at that moment. Adding an item later changes the next total.
- An empty cart has a total of
0. - An item with price 5 and quantity 3 has a subtotal of 15.
- Prices in the driver are whole numbers.
The driver (already in the starter code, don't change it) creates an empty cart, checks one subtotal, then fills a cart and prints the total twice:
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());
Expected output:
Empty: 0 Subtotal: 15 Total: 75 Total: 95
Declare the three typed fields at the top of
LineItem, then the constructor and subtotal().
this.items.reduce((s, it) => s + it.subtotal(), 0): s starts at 0 and grows by every item's subtotal.
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());
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
