While checking the test cases, I am able to get results as desired but the test cases are not passing through. I am not sure about the error in this case
let price = 11.95; // Example price, you can adjust this
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]
];
const currencyUnit = {
'PENNY': 0.01,
'NICKEL': 0.05,
'DIME': 0.1,
'QUARTER': 0.25,
'ONE': 1,
'FIVE': 5,
'TEN': 10,
'TWENTY': 20,
'ONE HUNDRED': 100
};
let cidForWork = [...cid]
// Enhance cid structure
for (let i = 0; i < cidForWork.length; i++) {
cidForWork[i].push(currencyUnit[cidForWork[i][0]]);
cidForWork[i].push(Math.floor(cidForWork[i][1] / cidForWork[i][2]));
}
const cashInHand = [...cidForWork].reverse();
const totalcid = cashInHand.reduce((acc, el) => acc + el[1], 0);
const outputElement = document.getElementById('change-due');
const purchasebtn = document.getElementById('purchase-btn');
let balance = 0;
const reset = () => {
balance = 0;
};
purchasebtn.addEventListener("click", (e) => {
e.preventDefault();
reset();
const input = parseFloat(document.getElementById('cash').value);
balance = input - price;
if (input < price) {
outputElement.innerText = "Customer does not have enough money to purchase the item";
alert("Customer does not have enough money to purchase the item")
return
} else if (input === price) {
outputElement.innerText = "No change due - customer paid with exact cash";
return
} else {
if (totalcid < balance) {
outputElement.innerText = "Status: INSUFFICIENT_FUNDS";
return
} else {
const calculatedChange = calculateChange(balance, cashInHand);
if (!calculatedChange) {
outputElement.innerText = "Status: INSUFFICIENT_FUNDS";
return
} else if (totalcid === balance) {
outputElement.innerText = "Status: CLOSED ";
outputElement.innerText += calculatedChange.map(array => array.join(": $")).join(" ");
} else {
outputElement.innerText = "Status: OPEN ";
outputElement.innerText += calculatedChange.map(array => array.join(": $")).join(" ");
}
}
}
});
const calculateChange = (balance, cidForFunc) => {
const changeArray = [];
for (let i = 0; i < cidForFunc.length; i++) {
let unitValue = cidForFunc[i][2];
let amountInDrawer = cidForFunc[i][1];
let unitCount = cidForFunc[i][3];
let amountToReturn = 0;
while (balance >= unitValue && unitCount > 0) {
amountToReturn += unitValue;
balance = (balance - unitValue).toFixed(2);
unitCount--;
}
if (amountToReturn > 0) {
changeArray.push([cidForFunc[i][0], parseFloat(amountToReturn.toFixed(2))]);
}
}
return balance > 0 ? null : changeArray;
};