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): voidaddsamountto the credit. It prints and returns nothing.select(): stringtries 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(): numberreturns 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:
insertadds to the credit.selectcompares the credit with the price. A failed purchase only reports what is missing. A successful one pays for the item by lowering the credit.refundmust 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
| Call | Result | Credit after |
|---|---|---|
insert(50) | nothing | 50 |
select() | Need 100 more | 50 |
insert(150) | nothing | 200 |
select() | Dispensing! | 50 |
refund() | 50 | 0 |
insert(150) | nothing | 150 |
select() | Dispensing! | 0 |
refund() | 0 | 0 |
insert(100) | nothing | 100 |
select() | Need 50 more | 100 |
refund() | 100 | 0 |
Step by step
- Declare the class
VendingMachineand write its closing brace at once. A class is a blueprint: each machine built from it keeps its own credit. - Add the field
credit: number = 0;, because a new machine holds no money. - Add the field
price: number = 150;, because every item costs 150. - Start
insertwith anumberparameter namedamountand the return typevoid. It only changes the machine's state. - Add
amounttothis.creditwith+=. Adding keeps the money already inside, where plain assignment would replace it. - Start
select, with no parameters and the return typestring, because it answers with text. - Handle too little money: if
this.credit < this.price, return"Need " + (this.price - this.credit) + " more". A one-lineifwith itsreturnis enough. A miss must not change the credit. - Subtract the price from the credit. This line is reached only when the credit covers the price. Skipping it would make
refundreturn too much. - Return
"Dispensing!". - Start
refund, with no parameters and the return typenumber. - Save the credit in
const r: number. Once the credit is reset, its old value is gone. - Set
this.creditback to 0. - 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,thisis the machine the method was called on. Callinga.insert(100)changesa.credit, and a second machinebstill 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 isNaN. The compiler reportsThe left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type, and the compiled program printsNaN 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.
insertisvoid, so it gives nothing back.selectandrefunddeclare the type they return, and the compiler checks everyreturnagainst it. constfor the saved value.ris never reassigned, soconstsays so. The annotation: numberwould be inferred anyway.- Fields are public. With no modifier,
creditandpricecan be read and written from outside. The driver's code could writem.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 answerNeed 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 morethe credit must still be 50. - Resetting before saving in
refund. Settingthis.credit = 0and then returningthis.creditalways 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 = amountloses 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,
numberarithmetic is inexact: after inserting 0.1 and 0.2,select()reportsNeed 149.7 moreand not a clean amount.
Testing
- A new machine:
refund()returns 0. insert(150)thenselect(): returnsDispensing!, and the credit afterwards is 0.insert(50)thenselect(): returnsNeed 100 moreand the credit stays 50.insert(200),select()and thenrefund():Dispensing!and a refund of 50.- Two refunds in a row after
insert(100): 100, then 0.
