Instantly share code, notes, and snippets.

Embed
What would you like to do?
Pseudocode for a vending machine "smart contract" in JavaScript
/**
* A pseudo VendingMachine "smart contract" in JavaScript
*
* See: https://newline.co
**/
class VendingMachine {
constructor() {
this.price = 50; // 50 cents for any soda
this.balance = 0; // number of cents paid so far
this.selection = null; // name of selected drink
this.inventory = {
sprite: 3,
coke: 10,
'dr pepper': 5
};
}
deposit(amount) {
this.balance = this.balance + amount;
this.maybeFinalize();
}
makeSelection(name) {
if (this.inventory[name] && this.inventory[name] > 0) {
this.selection = name;
this.maybeFinalize();
}
}
maybeFinalize() {
if (this.selection && this.balance >= this.price) {
// subtract balance
this.balance = this.balance - this.price;
// subtract inventory
this.inventory[this.selection] =
this.inventory[this.selection] - 1;
this.dispenseDrink(this.selection);
// clear the selection
this.selection = null;
this.refundBalance();
}
}
refundBalance() {
if (this.balance > 0) {
const refundAmount = this.balance;
this.balance = 0;
this.emitCoins(refundAmount);
}
}
dispenseDrink(name) {
// ... call hardware to dispense drink
console.log('Dispensing ' + name);
}
emitCoins(amount) {
if (amount > 0) {
// ... call hardware to emit coins
console.log('Refunding ' + amount);
}
}
}
const assert = require('assert');
let m = new VendingMachine();
// check initial state
assert(m.inventory.coke === 10);
assert(m.balance === 0);
assert(m.selection === null);
// buy a coke with exact change
m.deposit(25);
assert(m.inventory.coke === 10);
assert(m.balance === 25);
m.deposit(25);
assert(m.balance === 50);
m.makeSelection('coke');
assert(m.inventory.coke === 9);
assert(m.balance === 0);
assert(m.selection === null);
// make a selection first, put in extra money
m.makeSelection('coke');
m.deposit(25);
assert(m.inventory.coke === 9);
assert(m.balance === 25);
m.deposit(100);
assert(m.inventory.coke === 8);
assert(m.balance === 0);
console.log('Done');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment