please assist to check where the error could be in this code.I have redone it severally and it works well but three of the tests keeps failing.here is my code;
let cash = document.getElementById("cash");
let changeDue = document.getElementById("change-due");
const purchaseBtn = document.getElementById("purchase-btn");
const totalCidDisplay = document.getElementById("total-cid");
// Define the price
let price = 19.5;
// Define the cash-in-drawer array
let cid = [
{ name: "PENNY", amount: 1.01 },
{ name: "NICKEL", amount: 2.05 },
{ name: "DIME", amount: 3.1 },
{ name: "QUARTER", amount: 4.25 },
{ name: "ONE", amount: 90 },
{ name: "FIVE", amount: 55 },
{ name: "TEN", amount: 20 },
{ name: "TWENTY", amount: 60 },
{ name: "ONE HUNDRED", amount: 100 }
];
// Function to calculate the change
function calculateChange() {
let cashAmount = parseFloat(cash.value);
let changeAmount = cashAmount - price;
if (cashAmount < price) {
alert("Customer does not have enough money to purchase the item");
return;
} else if (changeAmount === 0) {
changeDue.textContent = "No change due - customer paid with exact cash";
return;
}
let change = [];
let remainingChange = changeAmount;
for (let i = cid.length - 1; i >= 0; i--) {
const denomination = cid[i];
const denominationValue = getDenomUnit(denomination.name);
let numOfDenomination = 0;
while (denominationValue <= remainingChange && denominationValue <= denomination.amount) {
remainingChange -= denominationValue;
denomination.amount -= denominationValue;
numOfDenomination++;
remainingChange = parseFloat(remainingChange.toFixed(2));
}
if (numOfDenomination > 0) {
change.push({ name: denomination.name, amount: numOfDenomination });
}
if (remainingChange === 0) {
break;
}
}
if (remainingChange !== 0) {
changeDue.textContent = "Status: INSUFFICIENT_FUNDS";
} else {
let changeString = "Status: OPEN ";
for (let denom of change) {
let denomAmount = denom.amount * getDenomUnit(denom.name);
if (denomAmount % 1 !== 0) {
denomAmount = denomAmount.toFixed(2).replace(/\.?0+$/, ''); // Replace trailing zeroes
}
changeString += denom.name + ": $" + denomAmount + " ";
}
changeDue.textContent = changeString.trim();
}
// Display total cash in drawer after calculation
totalCidDisplay.textContent = "Total Cash in Drawer: " + getTotalCashInDrawer(cid).toFixed(2);
}
// Function to calculate total cash in drawer
function getTotalCashInDrawer(cid) {
let total = 0;
for (let denomination of cid) {
total += denomination.amount;
}
return total;
}
// Helper function to get denomination value
const getDenomUnit = (denomName) => {
switch (denomName) {
case "PENNY":
return 0.01;
case "NICKEL":
return 0.05;
case "DIME":
return 0.1;
case "QUARTER":
return 0.25;
case "ONE":
return 1;
case "FIVE":
return 5;
case "TEN":
return 10;
case "TWENTY":
return 20;
case "ONE HUNDRED":
return 100;
default:
return 0;
}
};
// Event listener for button click
purchaseBtn.addEventListener("click", calculateChange);