|
| 1 | +var MoneyStack = function(billSize) { |
| 2 | + this.billSize = billSize |
| 3 | + this.next = null |
| 4 | +} |
| 5 | + |
| 6 | +MoneyStack.prototype = { |
| 7 | + withdraw: function(amount) { |
| 8 | + var numOfBills = Math.floor(amount / this.billSize) |
| 9 | + if (numOfBills > 0) { |
| 10 | + this._ejectMoney(numOfBills) // Eject the bills |
| 11 | + amount = amount - this.billSize * numOfBills // Shrink the amount by how much money we ejected |
| 12 | + } |
| 13 | + // If there is any money left to withdraw and if we have |
| 14 | + // another stack in the line, pass the request on |
| 15 | + amount > 0 && this.next && this.next.withdraw(amount) |
| 16 | + }, |
| 17 | + |
| 18 | + // set the stack that comes next in the chain |
| 19 | + setNextStack: function(stack) { |
| 20 | + this.next = stack |
| 21 | + }, |
| 22 | + |
| 23 | + // private method that ejects the money |
| 24 | + _ejectMoney: function(numOfBills) { |
| 25 | + console.log( |
| 26 | + numOfBills + ' $' + this.billSize + ' bill(s) has/have been spit out', |
| 27 | + ) |
| 28 | + }, |
| 29 | +} |
| 30 | + |
| 31 | +var ATM = function() { |
| 32 | + // Create the stacks of money |
| 33 | + // We'll show you the implementation for this next |
| 34 | + var stack100 = new MoneyStack(100) |
| 35 | + var stack50 = new MoneyStack(50) |
| 36 | + var stack20 = new MoneyStack(20) |
| 37 | + var stack10 = new MoneyStack(10) |
| 38 | + var stack5 = new MoneyStack(5) |
| 39 | + var stack1 = new MoneyStack(1) |
| 40 | + |
| 41 | + // Set the hierarchy for the stacks |
| 42 | + stack100.setNextStack(stack50) |
| 43 | + stack50.setNextStack(stack20) |
| 44 | + stack20.setNextStack(stack10) |
| 45 | + stack10.setNextStack(stack5) |
| 46 | + stack5.setNextStack(stack1) |
| 47 | + |
| 48 | + // Set the top stack as a property |
| 49 | + this.moneyStacks = stack100 |
| 50 | +} |
| 51 | + |
| 52 | +ATM.prototype.withdraw = function(amount) { |
| 53 | + this.moneyStacks.withdraw(amount) |
| 54 | +} |
| 55 | + |
| 56 | +// USAGE |
| 57 | +var atm = new ATM() |
| 58 | + |
| 59 | +console.log('===186===') |
| 60 | +atm.withdraw(186) |
| 61 | +/* outputs: |
| 62 | + 1 $100 bill(s) has/have been spit out |
| 63 | + 1 $50 bill(s) has/have been spit out |
| 64 | + 1 $20 bill(s) has/have been spit out |
| 65 | + 1 $10 bill(s) has/have been spit out |
| 66 | + 1 $5 bill(s) has/have been spit out |
| 67 | + 1 $1 bill(s) has/have been spit out |
| 68 | +*/ |
| 69 | + |
| 70 | +console.log('===72===') |
| 71 | +atm.withdraw(72) |
| 72 | +/* outputs: |
| 73 | + 1 $50 bill(s) has/have been spit out |
| 74 | + 1 $20 bill(s) has/have been spit out |
| 75 | + 2 $1 bill(s) has/have been spit out |
| 76 | +*/ |
0 commit comments