let price = 3.26;
let cid = [
['PENNY', 1.01],
['NICKEL', 2.05],
['DIME', 3.1],
['QUARTER', 4.25],
['ONE', 90],
['FIVE', 55],
['TEN', 20],
['TWENTY', 60],
['ONE HUNDRED', 100]
];
document.getElementById('purchase-btn').addEventListener('click', function() {
const cash = parseFloat(document.getElementById('cash').value);
const changeDue = (cash - price).toFixed(2);
const changeArr = [];
if (cash < price) {
alert("Customer does not have enough money to purchase the item");
return;
}
if (changeDue === "0.00") {
document.getElementById('change-due').innerText = "No change due - customer paid with exact cash";
return;
}
let totalCid = parseFloat(cid.reduce((acc, curr) => acc + curr[1], 0).toFixed(2));
if (parseFloat(changeDue) > totalCid) {
document.getElementById('change-due').innerText = "Status: INSUFFICIENT_FUNDS";
return;
}
let remainingChange = parseFloat(changeDue);
for (let i = cid.length - 1; i >= 0; i--) {
let coinName = cid[i][0];
let coinValue = cid[i][1];
let coinTotalValue = 0;
while (remainingChange >= getCoinValue(coinName) && coinValue > 0) {
remainingChange = (remainingChange - getCoinValue(coinName)).toFixed(2);
coinValue -= getCoinValue(coinName);
coinTotalValue += getCoinValue(coinName);
}
if (coinTotalValue > 0) {
changeArr.push([coinName, coinTotalValue]);
}
}
if (remainingChange > 0) {
document.getElementById('change-due').innerText = "Status: INSUFFICIENT_FUNDS";
} else {
if (totalCid - changeArr.reduce((acc, curr) => acc + curr[1], 0).toFixed(2) === "0.00") {
document.getElementById('change-due').innerText = "Status: CLOSED " + formatChange(cid);
} else {
document.getElementById('change-due').innerText = "Status: OPEN " + formatChange(changeArr);
}
}
});
function getCoinValue(coin) {
switch (coin) {
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;
}
}
function formatChange(changeArr) {
return changeArr.map(coin => `${coin[0]}: $${coin[1].toFixed(2)}`).join(" ");
}
unable to pass last two tests