Start learning free

LESSON 67 OF 68 · PROJECTS: OBJECT-ORIENTED

Vending Machine in JavaScript: A Class That Tracks Credit

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 class fields credit = 0; and price = 150;.
  • insert(amount) adds amount to the credit. Nothing is printed or returned.
  • select() 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() 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 = 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 = 0;
    price = 150;

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

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

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

STEP 1 OF 13
    Ctrl + Enter to check

    JAVASCRIPT · PROJECTS: OBJECT-ORIENTED

    Vending Machine in JavaScript, 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. It sells an item when the credit is enough and gives the remaining credit back on request. A new machine comes from new VendingMachine(), with credit 0 and price 150.

    • insert(amount) adds amount to the credit and returns nothing.
    • select() tries to buy one item and returns a string. If the credit is less than the price, it returns "Need N more", where N is price - credit, and the credit doesn't change. Otherwise it subtracts the price from the credit and returns "Dispensing!". Paying exactly 150 works, and any extra money stays in the credit.
    • refund() returns the whole credit and sets it back to 0.

    The driver inserts 50 and selects: that is 100 short. After 150 more the credit is 200, so the machine dispenses and keeps 50, which the refund returns. Then exact payment of 150 dispenses and refunds 0. Finally, 100 is 50 short, the credit stays 100, and the refund returns 100. The output is:

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

    Approach: state plus methods

    This is the basic shape of a class: some state, and methods that read or change it. The state here is two values, credit and price, declared as class fields. Every machine made from the class gets its own copy, so one machine's credit never leaks into another's.

    The methods then split into three kinds of behaviour. insert only changes state. select checks the state, and changes it only on a successful purchase. refund returns a value and resets the state. The two things to get right are keeping a failed purchase from touching the credit, and reading the credit before refund resets it.

    Step by step

    1. Declare the class VendingMachine. It is a blueprint, and each machine keeps its own credit.
    2. Add the field credit = 0;. A new machine holds no money.
    3. Add the field price = 150;. Every item costs 150.
    4. Write insert(amount). It adds amount to this.credit with +=: add to what is already there, don't replace it.
    5. Write select() and handle too little money first. If this.credit is less than this.price, return "Need " + (this.price - this.credit) + " more". This branch only reports; it never changes the credit.
    6. Subtract the price from the credit. This line is reached only when the credit covers the price, because the earlier return left the method otherwise.
    7. Return "Dispensing!".
    8. Write refund(). Save the current credit in a const named r, set this.credit back to 0, then return r.

    The solution in JavaScript

    class VendingMachine {
        credit = 0;
        price = 150;
        insert(amount) {
            this.credit += amount;
        }
        select() {
            if (this.credit < this.price) return "Need " + (this.price - this.credit) + " more";
            this.credit -= this.price;
            return "Dispensing!";
        }
        refund() {
            const r = this.credit;
            this.credit = 0;
            return r;
        }
    }
    let m = 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());
    

    The JavaScript details behind it:

    • Class fields. credit = 0; and price = 150; sit directly in the class body. They run when an object is created, and the values become properties of that object, reached as this.credit and this.price. Unlike these two, they are public: m.credit works from outside.
    • Parentheses around the subtraction. In "Need " + (this.price - this.credit) + " more" the parentheses make the subtraction happen first. Without them, JavaScript would join "Need " + this.price into a string and then subtract from that string, which gives NaN, so the message would read NaN more.
    • Numbers join text automatically. When + has a string on one side, the number on the other side is converted to text, which is how 100 becomes part of the message.
    • Why refund needs r. Writing this.credit = 0; return this.credit; would always return 0, because the old value is gone once it is overwritten. Saving it in a local constant first keeps it.
    • One-line if. if (...) return ...; without braces controls just that one statement. The statements after it run only when the condition was false.

    Edge cases and common mistakes

    • Subtracting the price when the credit is too low. The credit would go down on a refused purchase, and a later refund would be too small. The subtraction belongs after the early return.
    • Forgetting to subtract after a sale. The leftover credit would be wrong. In the driver, the first refund would return 200 instead of 50.
    • Using <= instead of <. Exact payment would be refused. With 150 inserted, the machine would answer Need 0 more instead of dispensing.
    • Nothing inserted yet. A new machine's select() returns Need 150 more, and its refund() returns 0.
    • Buying twice. With 300 inserted, the first select() dispenses and leaves 150, the second dispenses and leaves 0, and the third returns Need 150 more.
    • Refunding twice. After a refund the credit is 0, so asking again right away returns 0.
    • Off by one. With 149 inserted, select() returns Need 1 more and the credit stays 149. After inserting 1 more it dispenses.
    • Passing text. insert("50") turns the credit into the string "050", because 0 + "50" joins text. Insert real numbers.

    Testing

    • A new machine: select() returns Need 150 more.
    • Insert 150, then select(): Dispensing!, and credit is 0.
    • Insert 149, then select(): Need 1 more, and credit is 149.
    • Insert 40 twice, then select(): Need 70 more.
    • Insert 100, then call refund() twice: 100, then 0.
    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free