Start learning free

LESSON 412 OF 414 · PROJECTS: OBJECT-ORIENTED

Shopping Cart in TypeScript in TypeScript

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

  • Typed public fields name: string, price: number, quantity: number.
  • constructor(name: string, price: number, quantity: number) stores the three values in the fields.
  • subtotal(): number returns this.price * this.quantity.

Cart

  • It keeps its items in private items: LineItem[] = [] (private means only the class's own methods can use it).
  • add(item: LineItem): void pushes a LineItem onto the array.
  • total(): number returns the sum of the subtotals of all items, using reduce with start value 0, 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

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

STEP 1 OF 16
    Ctrl + Enter to check

    Shopping Cart in TypeScript

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