This seems to be returning the correct change on the second test, but not the first. I can’t figure out what is wrong with my code.
Update: I added some console logs and I think I found the problem. When finding the highestUnit it includes 20 four times and when I check
if (cid[unitIndex][1] >= highestUnit)
It skips the 4th 20 and leaves me with an incorrect change from that point. How can I fix this?
function checkCashRegister(price, cash, cid) {
let cashValues =[.01, .05, .1, .25, 1, 5, 10, 20, 100];
var index = 0;
var totalCash = 0;
var changeDue = 0;
var returnChange = [];
for (var i = 0; i < cid.length; i++) {
totalCash += cid[i][1];
}totalCash = totalCash.toFixed(2);
changeDue = cash - price;
if (changeDue > totalCash) {
return {status: "INSUFFICIENT_FUNDS", change: []}
}
if (changeDue == totalCash) {
return {status: "CLOSED", change: cid}
}
while (changeDue > 0) {
var highestUnit = Math.max.apply(Math, cashValues.filter(function(x){return x <= changeDue}
));
var unitIndex = cashValues.indexOf(highestUnit)
if (cid[unitIndex][1] >= highestUnit) {
returnChange.push([cid[unitIndex][0], highestUnit ]);
cid[unitIndex][1]=cid[unitIndex][1] - highestUnit;
}
changeDue = (changeDue - highestUnit).toFixed(2);
}
console.log(returnChange)
console.log(cid)
}
console.log(checkCashRegister(3.26, 100, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]]));
console.log(checkCashRegister(19.5, 20, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]]));