Created
August 3, 2022 14:01
-
-
Save ImaginaryDevelopment/24e6067f130ee1d57af27ae23a1091e3 to your computer and use it in GitHub Desktop.
FreeCodeCamp change calc
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
let getCidTotal = (cid) => | |
cid.map(x => x[1]).reduce((x,y) => x + y); | |
function payout(owed,dv,v){ | |
// if we have less than a d, or we owe less than a d skip | |
if(dv === 0.01) | |
console.log(JSON.stringify({owed,dv,v})); | |
if(v < dv || owed < dv) return; | |
var i = 0; | |
while(v >= dv && owed >= dv){ | |
console.log(JSON.stringify({owed,dv,v,i})); | |
i++; | |
// damned rounding error | |
v = (v - dv).toFixed(2); | |
owed = (owed - dv).toFixed(2); | |
} | |
if(i < 1) return; | |
if(dv === 0.01) | |
console.log(JSON.stringify({owed,dv,v})); | |
return {i, paid: i * dv}; | |
} | |
let dvMap = { | |
"ONE HUNDRED": 100, | |
"TWENTY": 20, | |
"TEN": 10, | |
"FIVE": 5, | |
"ONE": 1, | |
"QUARTER": 0.25, | |
"DIME": 0.10, | |
"NICKEL": 0.05, | |
"PENNY": 0.01 | |
}; | |
function checkCashRegister(price, cash, cid) { | |
let totalChangeNeeded = cash - price; | |
let owed = totalChangeNeeded; | |
let cidT = getCidTotal(cid); | |
//console.log(JSON.stringify({price,cash,owed,cidT})); | |
if(price > cash || owed > cidT) return {status: "INSUFFICIENT_FUNDS", change: []}; | |
if(owed == cidT) return {status:"CLOSED", change: cid}; | |
let rem = cid.map(x => [...x]).reverse(); | |
//console.log(JSON.stringify(rem)); | |
let resp = {status:'OPEN',change:[]}; | |
for(let i = 0; i < rem.length; i++){ | |
let [d,v] = rem[i]; | |
var dv = dvMap[d]; | |
var r = payout(owed,dv,v); | |
//console.log(JSON.stringify({d,v,resp,owed,dv})); | |
if(!r) continue; | |
if(r.i > 0){ | |
owed = Math.round(100 * (owed - r.paid)) / 100; | |
resp.change.push([d,r.paid]); | |
} | |
} | |
if(owed > 0.01){ | |
console.log(JSON.stringify({resp,totalChangeNeeded,owed})); | |
return {status:"INSUFFICIENT_FUNDS", change: []}; | |
} | |
return resp; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment