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
constructor(name, price, quantity)stores the three values inthis.name,this.priceandthis.quantity.subtotal()returnsthis.price * this.quantity, the money this one row adds up to.
Cart
- It keeps its items in a private field
#itemsthat starts as an empty array (the#makes it private to the class). add(item)pushes aLineItemonto#items.total()returns the sum of the subtotals of all items, usingreduce:this.#items.reduce((s, it) => s + it.subtotal(), 0). The0is where the sum starts, 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
Write
class LineItem with its constructor and subtotal() first, then class Cart with #items.
reduce keeps a running value s: it starts at 0 and, for every item, becomes s + it.subtotal().
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());
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
