Created
December 12, 2018 01:55
-
-
Save iCaspar/b88b65f1f56fd71ac01bb638f045da11 to your computer and use it in GitHub Desktop.
A cash register function
This file contains 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
function checkCashRegister(price, cash, cid) { | |
const denominationVals = { | |
'ONE HUNDRED': 100, | |
'TWENTY': 20, | |
'TEN': 10, | |
'FIVE': 5, | |
'ONE': 1, | |
'QUARTER': 0.25, | |
'DIME': 0.1, | |
'NICKEL': 0.050, | |
'PENNY': 0.010 | |
} | |
let changeSpecifics = { | |
status: 'OPEN', | |
change: [] | |
} | |
let changeAmt = cash - price | |
let slot = cid.length | |
let slotAmts = [] | |
while (slot-- > 0) { | |
let slotVal = denominationVals[cid[slot][0]] | |
if (changeAmt >= slotVal) { | |
let changeFromSlot = 0 | |
let slotAmt = cid[slot][1] | |
while (slotAmt && (changeAmt >= slotVal)) { | |
changeFromSlot += slotVal | |
changeAmt -= slotVal | |
slotAmt -= slotVal | |
// Fix js rounding errors after subtracting floats | |
changeAmt = Math.round(changeAmt * 100) / 100 | |
slotAmt = Math.round(slotAmt * 100) / 100 | |
} | |
slotAmts.push(slotAmt) | |
changeSpecifics.change.push([cid[slot][0], changeFromSlot]) | |
} | |
} | |
if (changeAmt > 0) { | |
changeSpecifics.status = 'INSUFFICIENT_FUNDS' | |
changeSpecifics.change = [] | |
return changeSpecifics | |
} | |
let allGone = true | |
for (slot in slotAmts) { | |
if (slotAmts[slot] > 0) { | |
allGone = false | |
} | |
} | |
if (allGone === true) { | |
changeSpecifics.status = 'CLOSED' | |
changeSpecifics.change = cid | |
return changeSpecifics | |
} | |
return changeSpecifics | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment