Hello,
Could anyone have a look at my code and see if they can identify the problem?
It passes the challenge but it doesn’t give me the correct output for the example below.
Please also make any comment you wish to about the my code. I know it is quite messy.
Thank you.
function checkCashRegister(price, cash, cid) {
let changeDue = cash - price;
let changeArr = [100, 20, 10, 5, 1, 0.25, 0.10, 0.05, 0.01]
let arrRet = {status: "" , change: []};
cid.reverse();
let total = 0;
for(let i = 0; i < cid.length; i++){
total = total + cid[i][1];
}
let total2 = total;
for(let i = 0; i < cid.length; i++){
total2 = total2 - cid[i][1];
let num = (changeDue.toFixed(2)/changeArr[i]).toString().split(".")[0];
if(num >= 1 && num * changeArr[i] < cid[i][1] && cid[i][1] !== 0 && total !== changeDue && total >= changeDue){
arrRet.status = `OPEN`;
cid[i] = [cid[i][0], num * changeArr[i]];
arrRet.change.push(cid[i]);
changeDue = changeDue - num * changeArr[i];
total = total - num * changeArr[i];
if(changeDue === 0){
break;
}
} else if(num >= 1 && num * changeArr[i] >= cid[i][1] && cid[i][1] !== 0 && total !== changeDue && total >= changeDue && total2 >= changeDue){
arrRet.status = `OPEN`;
arrRet.change.push(cid[i] );
changeDue = changeDue - cid[i][1];
total = total - cid[i][1];
} else if(total == changeDue){
arrRet.status = `CLOSED`;
arrRet.change = cid.reverse();
} else if(total < changeDue || total2 < changeDue) {
arrRet.status = `INSUFFICIENT_FUNDS`;
arrRet.change = [];
}
}
return arrRet;
}
checkCashRegister(3.26, 10000, [["PENNY", 10.01], ["NICKEL", 20.05], ["DIME", 30.1], ["QUARTER", 400.25], ["ONE", 900], ["FIVE", 555], ["TEN", 2000], ["TWENTY", 6000], ["ONE HUNDRED", 2000]])
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36
.
Challenge: Cash Register
Link to the challenge: