I am learning Javascript through FreeCodeCamp. Managed to complete the whole course, but one test is failing on the final challenge.
This is a Javascript Cash Register that accepts 3 arguments: Price, Cash, Cash in the drawer of the till. It should calculate the change to be returned, and returning this as an object, with the status and change values. All tests pass and return the correct value, apart from the below:
checkCashRegister(19.5, 20, [["PENNY", 0.5], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]])
Is currently returning
{ status: 'INSUFFICIENT_FUNDS', change: [] }
should return
return {status: "CLOSED", change: [["PENNY", 0.5], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]]}.
I believe the issue is with returning ["PENNY", 0.5]. Or something to do with the costDiff variable.
Please see my code below:
function checkCashRegister(price, cash, cid) {
let currencies = [
["ONE HUNDRED", 10000],
["TWENTY", 2000],
["TEN", 1000],
["FIVE", 500],
["ONE", 100],
["QUARTER", 25],
["DIME", 10],
["NICKEL", 5],
["PENNY", 1]
];
let change = [];
let status = "";
// How much change is needed
let costDiff = cash * 100 - price * 100;
let costDiffCopy = costDiff;
// What money types and amount is in the till
let tillCash = cid.filter(money =>money[1] > 0).reverse();
// How much total money is in the till
let tillTotal = 0;
for (let i =0; i < tillCash.length; i++){
let cashSum = tillCash[i][1]*100;
tillTotal += cashSum;
let changeAmount = 0;
while(costDiff >= currencies[i][1] && cashSum > 0){
costDiff -= currencies[i][1];
cashSum -= currencies[i][1];
changeAmount += currencies[i][1];
}
if (changeAmount !== 0){
change.push([tillCash[i][0],changeAmount / 100]);
}
};
if (costDiff > 0){
status = "INSUFFICIENT_FUNDS";
change = [];
} else if (costDiff == 0 && costDiffCopy == tillTotal){
status = "CLOSED";
change = cid;
} else {
status = "OPEN";
}
let result = {"status": status, "change": change};
return result;
}
I have been really stumped on this. Thank you so much in advance.