Tell us what’s happening:
My cash register seems to be working as it should, but im not able to pass the tests. can someone please help me?
Your code so far
document.addEventListener("DOMContentLoaded", function () {
const purchaseBtn = document.getElementById("purchase-btn");
const changeDueDiv = document.getElementById("change-due");
const cashInput = document.getElementById("cash");
const totalElement = document.getElementById("total");
let price = 19.5;
const cid = [
["PENNY", 1.01],
["NICKEL", 2.05],
["DIME", 3.1],
["QUARTER", 4.25],
["ONE", 90],
["FIVE", 55],
["TEN", 20],
["TWENTY", 60],
["ONE HUNDRED", 100],
];
function updateTotalDisplay() {
totalElement.textContent = `Total: $${price.toFixed(2)}`;
}
updateTotalDisplay();
purchaseBtn.addEventListener("click", function () {
const cash = parseFloat(cashInput.value);
if (isNaN(cash) || cash < 0) {
alert("Please enter a valid amount of cash.");
return;
}
let changeDue = cash - price;
if (changeDue < 0) {
alert("Customer does not have enough money to purchase the item.");
return;
} else if (changeDue === 0) {
changeDueDiv.innerHTML = "No change due - customer paid with exact cash.";
return;
}
const changeGiven = calculateChange(changeDue, cid);
if (!changeGiven) {
changeDueDiv.innerHTML = "Status: INSUFFICIENT_FUNDS";
} else {
let displayText =
"Status: " + (changeGiven.length > 0 ? "OPEN" : "CLOSED") + "<br>";
changeGiven.forEach(([denom, amount], index) => {
displayText += `${denom}: $${amount.toFixed(2)}`;
if (index < changeGiven.length - 1) {
displayText += "<br>"; // Add a line break after each denomination except the last one
}
});
changeDueDiv.innerHTML = displayText; // Use innerHTML to include HTML tags
}
});
function calculateChange(changeDue, cid) {
const currencyUnitValues = {
"ONE HUNDRED": 100.0,
"TWENTY": 20.0,
"TEN": 10.0,
"FIVE": 5.0,
"ONE": 1.0,
"QUARTER": 0.25,
"DIME": 0.1,
"NICKEL": 0.05,
"PENNY": 0.01,
};
let totalCID = cid.reduce((acc, curr) => acc + curr[1], 0);
let change = [];
if (changeDue > totalCID) {
return null;
}
cid = cid.reverse();
for (let [unit, amount] of cid) {
let value = currencyUnitValues[unit];
let total = 0;
while (changeDue >= value && amount > 0) {
changeDue -= value;
amount -= value;
total += value;
changeDue = Math.round(changeDue * 100) / 100;
}
if (total > 0) {
change.push([unit, total]);
}
}
if (changeDue > 0) {
return null;
}
return change;
}
});
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.2.1 Safari/605.1.15
Challenge Information:
Build a Cash Register Project - Build a Cash Register