I am currently working the Cash Register project in the javascript course here on freecodecamp. I have tried several different solutions, but I can’t get the last part right.
The function will return an object with the currency that you are supposed to receive back from the cash register, but it is individually separated from each other. For example, where you are supposed to get two quarters back, it should be QUARTER: 50, not two QUARTER: 25.
Therefore I made a for loop with an if function right before returning the change. It is supposed to look forward and check if it has the same name as the current, and then add the sums into one array and delete the other. I think there might be a problem with deleting them since the i in the for loop is not correct.
Is there any smart solution to this? I know that I could solve the whole project in a different way, but I did not understand the other methods that I have seen.
function checkCashRegister(price, cash, cid) {
let changeTotal = cash - price; //Total amount of change
let change = []; //Array with currency change
let cidTotal = 0;
for (let i in cid) {cidTotal += cid[i][1];} //Total amount in cash-drawer
cidTotal = Math.round(cidTotal*100)/100; //Round number to two decimals
//Check if sufficient funds or closed before calculating change
if (cidTotal < changeTotal) {return {status: "INSUFFICIENT_FUNDS", change: []} }
else if (cidTotal === changeTotal) {change = cid; return {status: "CLOSED", change} }
let currency = [100, 20, 10, 5, 1, 0.25, 0.1, 0.05, 0.01]; //Actual value
cid.reverse(); //Reverse to get highest currency first
for (let i in cid) {
while (changeTotal >= currency[i] && cid[i][1] > 0) {
change.push([cid[i][0], currency[i]]);
changeTotal -= currency[i];
cid[i][1] -= currency[i];
}
}
//Fix for the change array / the issue of this topic
for (let i = 0; i < change.length -1; i++) {
if (change[i][0] === change[i+1][0]) {
change[i][1] += change[i+1][1];
change.splice(i+1, 1)
}
}
return {status: "OPEN", change};
}
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]])
// should return
// {status: "OPEN", change: [["TWENTY", 60], ["TEN", 20], ["FIVE", 15], ["ONE", 1], ["QUARTER", 0.5], ["DIME", 0.2], ["PENNY", 0.04]]}