Last active
December 13, 2020 13:16
-
-
Save jashmenn/06339ef9fb32fda2b4f78dce80af9147 to your computer and use it in GitHub Desktop.
Pseudocode for a vending machine "smart contract" in JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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