Start learning free

LESSON 68 OF 70 · PROJECTS: OBJECT-ORIENTED

Vending Machine in TypeScript: A Class with State and Methods

Practice Read the full explanation

Build a VendingMachine class for a machine that sells one kind of item for a fixed price. It keeps the money inserted so far (the credit), sells an item when the credit is enough, and gives the remaining credit back on request. A new object is made with new VendingMachine().

Rules:

  • State. A new machine has credit 0 and price 150 (every item costs 150). Declare the typed fields credit: number = 0; and price: number = 150;.
  • insert(amount: number): void adds amount to the credit. Nothing is printed or returned.
  • select(): string tries to buy one item and returns a string:
    • If the credit is less than the price, return "Need N more", where N is the missing amount (price - credit) as a whole number, for example "Need 100 more". The credit does not change.
    • Otherwise (the credit is equal to or greater than the price, so exact payment works), subtract the price from the credit and return "Dispensing!". Any extra money stays in the credit.
  • refund(): number returns the whole credit and sets it back to 0, so asking again right away returns 0.

You start with this driver below your code:

let m: VendingMachine = new VendingMachine();
m.insert(50);
console.log(m.select());
m.insert(150);
console.log(m.select());
console.log("Refunded: " + m.refund());
m.insert(150);
console.log(m.select());
console.log("Refunded: " + m.refund());
m.insert(100);
console.log(m.select());
console.log("Refunded: " + m.refund());

Walk through it: 50 is not enough, so you see Need 100 more. After 150 more the credit is 200, so the machine dispenses and keeps 50 (200 - 150), and the refund is 50. Then 150 is exact payment: it dispenses and the refund is 0. Finally 100 is short by 50, the credit stays 100, and the refund is 100.

Expected output:

Need 100 more
Dispensing!
Refunded: 50
Dispensing!
Refunded: 0
Need 50 more
Refunded: 100

Join the missing amount into the text with +: "Need " + (this.price - this.credit) + " more". Do the subtraction only when the item is dispensed, not when the credit is too low. If you forget it, the leftover credit is wrong and the refund is too big.

In the refund method, save the credit first, then reset it to 0, then return what you saved. Return the saved constant, not this.credit.

class VendingMachine {
    credit: number = 0;
    price: number = 150;

    insert(amount: number): void {
        this.credit += amount;
    }

    select(): string {
        if (this.credit < this.price) return "Need " + (this.price - this.credit) + " more";
        this.credit -= this.price;
        return "Dispensing!";
    }

    refund(): number {
        const r: number = this.credit;
        this.credit = 0;
        return r;
    }
}

STEP 1 OF 13
    Ctrl + Enter to check

    TYPESCRIPT · PROJECTS: OBJECT-ORIENTED

    Vending Machine in TypeScript, explained

    Problem overview

    The lesson asks for a VendingMachine class for a machine that sells one kind of item at a fixed price. The machine remembers the money inserted so far, called the credit. Its behavior comes from three methods:

    • insert(amount: number): void adds amount to the credit. It prints and returns nothing.
    • select(): string tries to buy one item. When the credit is less than the price it returns "Need N more", where N is the missing amount, and leaves the credit alone. Otherwise it subtracts the price from the credit and returns "Dispensing!". Exact payment works, and extra money stays in the credit.
    • refund(): number returns the whole credit and sets it back to 0, so a second refund right away returns 0.

    A new machine has credit 0 and price 150. In the driver, 50 is inserted and select() says Need 100 more. Then 150 more makes the credit 200: the machine dispenses and keeps 50, so the refund is 50. Next, 150 is exact payment: it dispenses and the refund is 0. Finally 100 is 50 short, the credit stays 100 and the refund is 100.

    Approach: state in fields, behavior in methods

    A class bundles state, the data an object remembers, with methods, the actions that read or change it. Here the state is two numbers. credit changes over time. price is set when the machine is created and nothing in the lesson changes it. Every machine made with new VendingMachine() gets its own copy of both fields, so two machines don't affect each other.

    Each method is a small rule on that state:

    • insert adds to the credit.
    • select compares the credit with the price. A failed purchase only reports what is missing. A successful one pays for the item by lowering the credit.
    • refund must hand back the old credit and also reset it. Resetting first would lose the number, so the old value is saved in a local variable before the reset.

    Subtracting the price on success is what makes extra money stay in the machine. After the 200 purchase above, the credit is 200 - 150 = 50, and the next refund returns that 50.

    Tracing the driver

    CallResultCredit after
    insert(50)nothing50
    select()Need 100 more50
    insert(150)nothing200
    select()Dispensing!50
    refund()500
    insert(150)nothing150
    select()Dispensing!0
    refund()00
    insert(100)nothing100
    select()Need 50 more100
    refund()1000

    Step by step

    1. Declare the class VendingMachine and write its closing brace at once. A class is a blueprint: each machine built from it keeps its own credit.
    2. Add the field credit: number = 0;, because a new machine holds no money.
    3. Add the field price: number = 150;, because every item costs 150.
    4. Start insert with a number parameter named amount and the return type void. It only changes the machine's state.
    5. Add amount to this.credit with +=. Adding keeps the money already inside, where plain assignment would replace it.
    6. Start select, with no parameters and the return type string, because it answers with text.
    7. Handle too little money: if this.credit < this.price, return "Need " + (this.price - this.credit) + " more". A one-line if with its return is enough. A miss must not change the credit.
    8. Subtract the price from the credit. This line is reached only when the credit covers the price. Skipping it would make refund return too much.
    9. Return "Dispensing!".
    10. Start refund, with no parameters and the return type number.
    11. Save the credit in const r: number. Once the credit is reset, its old value is gone.
    12. Set this.credit back to 0.
    13. Return r, which still holds the money to give back.

    The solution in TypeScript

    class VendingMachine {
        credit: number = 0;
        price: number = 150;
    
        insert(amount: number): void {
            this.credit += amount;
        }
    
        select(): string {
            if (this.credit < this.price) return "Need " + (this.price - this.credit) + " more";
            this.credit -= this.price;
            return "Dispensing!";
        }
    
        refund(): number {
            const r: number = this.credit;
            this.credit = 0;
            return r;
        }
    }
    
    let m: VendingMachine = new VendingMachine();
    m.insert(50);
    console.log(m.select());
    m.insert(150);
    console.log(m.select());
    console.log("Refunded: " + m.refund());
    m.insert(150);
    console.log(m.select());
    console.log("Refunded: " + m.refund());
    m.insert(100);
    console.log(m.select());
    console.log("Refunded: " + m.refund());
    

    It prints:

    Need 100 more
    Dispensing!
    Refunded: 50
    Dispensing!
    Refunded: 0
    Need 50 more
    Refunded: 100
    

    TypeScript details worth knowing

    • Fields and initializers. credit: number = 0; declares the field's type and gives it a start value, which runs once for each new object. No constructor is needed: with none written, new VendingMachine() just runs the initializers.
    • this. Inside a method, this is the machine the method was called on. Calling a.insert(100) changes a.credit, and a second machine b still has a credit of 0.
    • The parentheses in the message matter. In "Need " + (this.price - this.credit) + " more", the subtraction is done first and its result is joined to the text. Without the parentheses, "Need " + this.price - this.credit + " more" reads left to right: the text "Need 150" minus a number is NaN. The compiler reports The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type, and the compiled program prints NaN more.
    • Joining a number to text. Using + with a string on one side turns the number into text, so no conversion call is needed. "Refunded: " + m.refund() works the same way.
    • Return types. insert is void, so it gives nothing back. select and refund declare the type they return, and the compiler checks every return against it.
    • const for the saved value. r is never reassigned, so const says so. The annotation : number would be inferred anyway.
    • Fields are public. With no modifier, credit and price can be read and written from outside. The driver's code could write m.credit = 1000. The lesson doesn't hide them.

    Complexity

    Each method does a constant amount of work: one comparison, one addition or subtraction, or one assignment. Every call is O(1) in time, and a machine stores two numbers, so the space is O(1).

    Edge cases and common mistakes

    • Exact payment. With a credit of exactly 150, select() must dispense and leave a credit of 0. Using <= in the guard would wrongly answer Need 0 more.
    • Forgetting to subtract the price. The machine would dispense but keep the whole credit, and the refund would return the full amount as if nothing had been bought. Selling twice in a row would also work on one payment.
    • Changing the credit on a failed purchase. A miss only reports the missing amount. After Need 100 more the credit must still be 50.
    • Resetting before saving in refund. Setting this.credit = 0 and then returning this.credit always returns 0.
    • Forgetting the reset. A second refund would hand the same money out again, instead of returning 0.
    • Replacing instead of adding in insert. this.credit = amount loses earlier coins.
    • Extra credit buys more. One select() sells a single item. With a credit of 200, select() dispenses once and the credit left is 50. A credit of 300 could buy twice, one call each.
    • Decimal money. The amounts are whole numbers. With decimals, number arithmetic is inexact: after inserting 0.1 and 0.2, select() reports Need 149.7 more and not a clean amount.

    Testing

    • A new machine: refund() returns 0.
    • insert(150) then select(): returns Dispensing!, and the credit afterwards is 0.
    • insert(50) then select(): returns Need 100 more and the credit stays 50.
    • insert(200), select() and then refund(): Dispensing! and a refund of 50.
    • Two refunds in a row after insert(100): 100, then 0.
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free