Tell us what’s happening:
For some reason my for loop that iterates backwards through cid seems to run several times. I’ve used a lot of console.log() commands to keep track of certain values. When I look at the console after running this, I see i get to 0, but the log is showing that i resets itself to 8 several times and executing the loop more than once.
Your code so far
function checkCashRegister(price, cash, cid) {
var amounts = {"PENNY": 0.01,
"NICKEL": 0.05,
"DIME": 0.10,
"QUARTER": 0.25,
"ONE": 1,
"FIVE": 5,
"TEN": 10,
"TWENTY": 20,
"ONE HUNDRED": 100};
var change = 0;
var cidAmount = 0;
var changeDue = cash - price;
var changeCid = [];
cid.forEach(function(item){
cidAmount += item[1];
});
cidAmount = Math.round(cidAmount * 100) / 100;
if(cidAmount == changeDue){
return "Closed";
}
else if(cidAmount < changeDue){
return "Insufficient Funds";
}
console.log(cid.length);
for(var i = cid.length-1; i > 0; i--){
console.log(i + " = i");
var bill = cid[i][1];//amount of current bill in drawer
console.log(bill + ": Bill");
var amount = amounts[cid[i][0]]; //denomination of bill
console.log(amount + ": amount");
var numOfBill = Math.floor(changeDue/amount); //number of bills to give
if(numOfBill * amount > bill){
numOfBill = bill/amount;
}
console.log(changeDue);
console.log(numOfBill+ ": num");
if(numOfBill > 0 && changeDue !== 0){
changeCid.push(cid[i][0], amount * numOfBill);
changeDue -= amount * numOfBill;
}
}
if(changeDue < 0.01){
return changeCid;
}
return "Insufficient Funds";
}
// 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(3.26, 100.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]]);
Your browser information:
Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36
.
Link to the challenge:
https://www.freecodecamp.org/challenges/exact-change