Start learning free

LESSON 408 OF 410 · PROJECTS: OBJECT-ORIENTED

Shopping Cart in JavaScript in JavaScript

Practice

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 in this.name, this.price and this.quantity.
  • subtotal() returns this.price * this.quantity, the money this one row adds up to.

Cart

  • It keeps its items in a private field #items that starts as an empty array (the # makes it private to the class).
  • add(item) pushes a LineItem onto #items.
  • total() returns the sum of the subtotals of all items, using reduce: this.#items.reduce((s, it) => s + it.subtotal(), 0). The 0 is where the sum starts, so an empty cart gives 0.

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());

STEP 1 OF 13
    Ctrl + Enter to check

    Shopping Cart in JavaScript

    Keep going with JavaScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free