Created
June 7, 2017 15:28
-
-
Save iamads/aaa672e6d3e0b65ef8af775cac46b102 to your computer and use it in GitHub Desktop.
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
var register = [ | |
{ | |
name: "PENNY", | |
value: 0.01, | |
count: 0 | |
}, | |
{ | |
name: "NICKEL", | |
value: 0.05, | |
count: 0 | |
}, | |
{ | |
name: "DIME", | |
value: 0.1, | |
count: 0 | |
}, | |
{ | |
name: "QUARTER", | |
value: 0.25, | |
count: 0 | |
}, | |
{ | |
name: "ONE", | |
value: 1, | |
count: 0 | |
}, | |
{ | |
name: "FIVE", | |
value: 5, | |
count: 0 | |
}, | |
{ | |
name: "TEN", | |
value: 10, | |
count: 0 | |
}, | |
{ | |
name: "TWENTY", | |
value: 20, | |
count: 0 | |
}, | |
{ | |
name: "ONE HUNDRED", | |
value: 100, | |
count: 0 | |
} | |
]; | |
function checkCashRegister(price, cash, cid) { | |
var change, total_cash; | |
// Here is your change, ma'am. | |
change = cash - price; | |
total_cash = cid.reduce(function(sum, x) { | |
return sum +x[1]; | |
}, 0); | |
if (change.toFixed(2) === total_cash.toFixed(2)) { | |
return "Closed"; | |
} | |
cid.forEach(function(denomination){ | |
register.forEach(function(wtf, index) { | |
if (wtf.name === denomination[0]) { | |
register[index].count = Math.ceil(denomination[1] / register[index].value); | |
} | |
}); | |
}); | |
register = register.reverse(); | |
answer = []; | |
register.forEach(function(den){ | |
if (change > den.value) { | |
quotient = change / den.value; | |
remainder = change % den.value; | |
used = quotient > den.count ? den.count: quotient; | |
change = change - (used * den.value).toFixed(2); | |
answer.unshift([den.name, (used * den.value)]) | |
} | |
}) | |
if (change !== 0 ) { | |
return "Insufficient Funds" | |
} | |
//console.log( JSON.stringify(answer, null, 2)); | |
return answer; | |
} | |
// Example cash-in-drawer array: | |
// [["PENNY", 1.01], | |
// ["NICKEL", 2.05], | |
// ["DIME", 3.10], | |
// ["QUARTER", 4.25], | |
// ["ONE", 90.00], | |
// ["FIVE", 55.00], | |
// ["TEN", 20.00], | |
// ["TWENTY", 60.00], | |
// ["ONE HUNDRED", 100.00]] | |
//checkCashRegister(19.50, 20.00, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.10], ["QUARTER", 4.25], ["ONE", 90.00], ["FIVE", 55.00], ["TEN", 20.00], ["TWENTY", 60.00], ["ONE HUNDRED", 100.00]]); | |
checkCashRegister(19.50, 20.00, [["PENNY", 0.50], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]]) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment