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)addsamountto 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 isprice - 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
- Declare the class
VendingMachine. It is a blueprint, and each machine keeps its own credit. - Add the field
credit = 0;. A new machine holds no money. - Add the field
price = 150;. Every item costs 150. - Write
insert(amount). It addsamounttothis.creditwith+=: add to what is already there, don't replace it. - Write
select()and handle too little money first. Ifthis.creditis less thanthis.price, return"Need " + (this.price - this.credit) + " more". This branch only reports; it never changes the credit. - Subtract the price from the credit. This line is reached only when the credit covers the price, because the earlier
returnleft the method otherwise. - Return
"Dispensing!". - Write
refund(). Save the current credit in aconstnamedr, setthis.creditback to 0, then returnr.
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;andprice = 150;sit directly in the class body. They run when an object is created, and the values become properties of that object, reached asthis.creditandthis.price. Unlike these two, they are public:m.creditworks 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.priceinto a string and then subtract from that string, which givesNaN, so the message would readNaN more. - Numbers join text automatically. When
+has a string on one side, the number on the other side is converted to text, which is how100becomes part of the message. - Why
refundneedsr. Writingthis.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 answerNeed 0 moreinstead of dispensing. - Nothing inserted yet. A new machine's
select()returnsNeed 150 more, and itsrefund()returns 0. - Buying twice. With 300 inserted, the first
select()dispenses and leaves 150, the second dispenses and leaves 0, and the third returnsNeed 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()returnsNeed 1 moreand the credit stays 149. After inserting 1 more it dispenses. - Passing text.
insert("50")turns the credit into the string"050", because0 + "50"joins text. Insert real numbers.
Testing
- A new machine:
select()returnsNeed 150 more. - Insert 150, then
select():Dispensing!, andcreditis 0. - Insert 149, then
select():Need 1 more, andcreditis 149. - Insert 40 twice, then
select():Need 70 more. - Insert 100, then call
refund()twice:100, then0.
