Start learning free

LESSON 67 OF 70 · PROJECTS: OBJECT-ORIENTED

Shopping Cart in TypeScript: LineItem and Cart Classes

Practice Read the full explanation

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

    TYPESCRIPT · PROJECTS: OBJECT-ORIENTED

    Shopping Cart in TypeScript, explained

    Problem overview

    A shop keeps its orders in a cart. The lesson asks for two classes that work together:

    • LineItem is one row of the cart: a product name, a price and a quantity. Its subtotal() method returns price * quantity.
    • Cart holds many rows in a private array. add(item) appends a row and total() 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

    1. Declare LineItem and write its closing brace at once.
    2. Declare three fields: name: string, price: number and quantity: number. TypeScript needs every field and its type declared in the class body before the constructor can assign it.
    3. Add the constructor with the same three values as parameters: name as a string, price and quantity as numbers.
    4. Store each parameter in its field with this.name = name; and the matching lines for price and quantity. Without this. the assignment would only touch the parameter, and the value would vanish when the constructor ends.
    5. Add subtotal() returning a number: this.price * this.quantity.
    6. Declare Cart below LineItem, with its closing brace.
    7. Declare the field private items: LineItem[] = [];. The type says "an array of LineItem", the initializer gives each cart its own empty array, and private means that only the cart's methods can use it.
    8. Add add(item: LineItem): void and push the item onto this.items. The array keeps the rows in the order they came in.
    9. Add total(): number and return this.items.reduce(...) with a callback that adds it.subtotal() to the running sum s, and with 0 as 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 reduce runs. For the cart with apple and bread, the sum starts at 0. The first row adds 15 and the second adds 60, so total() 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 it is a LineItem, because this.items is a LineItem[], and that s is a number, because the start value is 0. That is why it.subtotal() is checked without any annotation on the callback.
    • Rows are shared, not copied. add stores the object that was passed in. In the driver, apple goes into the cart and is still the same object. If you then write apple.quantity = 4, the cart's next total() is 100 instead of 95, because the total is computed from the rows' current values.
    • Public against private. The LineItem fields have no modifier, so they are public. items in Cart is private: using cart.items outside the class gets a compiler error, while the methods add and total are the intended way in.
    • Field initializers. = [] runs once for each new Cart, 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.1 and a quantity of 3, subtotal() returns 0.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. reduce without the 0 uses the first row as the starting sum, so the first row itself, a LineItem, would be added to a number. On an empty array, reduce with no start value throws a TypeError: Reduce of empty array with no initial value. With 0, an empty cart returns 0.
    • Adding prices instead of subtotals. Summing it.price ignores the quantities. The apple row would count 5 instead of 15.
    • Storing the total in a field. If add updated a total field, 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 stays undefined.
    • 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 to Cart, subtotal() to LineItem. 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.
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free