Tell us what’s happening:
I have tried everything I know to pass this. I have even enlisted the help of chat GPT to see if it could solve the problems. When I try the tests on my own, they seem to work fine, but when I run the tests I don’t pass the majority of them.
Your code so far
<!-- file: index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cash Register App</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Cash Register App</h1>
<!-- Input fields for price and cash -->
<div class="input-group">
<label for="price">Price:</label>
<input type="number" id="price" placeholder="Enter item price">
</div>
<div class="input-group">
<label for="cash">Cash Provided:</label>
<input type="number" id="cash" placeholder="Enter cash provided">
</div>
<!-- Button to complete the purchase -->
<button id="purchase-btn">Complete Purchase</button>
<!-- Output for change due -->
<h2>Change Due</h2>
<p id="change-due"></p>
<script src="script.js" defer></script>
</body>
</html>
/* file: script.js */
// Define constants for currency denominations
const CURRENCY_UNITS = [
{ name: "ONE HUNDRED", value: 100.0 },
{ name: "TWENTY", value: 20.0 },
{ name: "TEN", value: 10.0 },
{ name: "FIVE", value: 5.0 },
{ name: "ONE", value: 1.0 },
{ name: "QUARTER", value: 0.25 },
{ name: "DIME", value: 0.1 },
{ name: "NICKEL", value: 0.05 },
{ name: "PENNY", value: 0.01 }
];
// Global variables
let price = 0;
let cid = [];
// Function to ensure all required elements exist
function ensureElementExists(id, defaultValue = "0") {
let element = document.getElementById(id);
if (!element) {
console.warn(`Element with ID '${id}' is missing. Creating it.`);
element = document.createElement("input");
element.id = id;
element.type = "number";
element.value = defaultValue;
element.style.display = "none"; // Hide dynamically created elements
document.body.appendChild(element);
}
if (typeof element.value === "undefined") {
console.warn(`Element with ID '${id}' has undefined value. Resetting to '${defaultValue}'.`);
element.value = defaultValue;
}
return element;
}
// Initialize all required elements
function initializeElements() {
ensureElementExists("price");
ensureElementExists("cash");
["penny", "nickel", "dime", "quarter", "one", "five", "ten", "twenty", "one-hundred"].forEach(id =>
ensureElementExists(id)
);
}
// Function to safely parse and trim input values
function safeParseInput(id) {
const element = ensureElementExists(id);
const value = (element.value || "0").toString();
console.log(`Parsing value for ID '${id}': '${value}'`); // Debug parsed value
return parseFloat(value.trim()) || 0;
}
// Function to calculate the change and update the status
function calculateChange(price, cash, cid) {
let changeDue = cash - price;
const totalCid = cid.reduce((sum, curr) => sum + curr[1], 0).toFixed(2);
let changeArray = [];
if (changeDue > totalCid) {
return "Status: INSUFFICIENT_FUNDS";
}
if (Number(changeDue.toFixed(2)) === Number(totalCid)) {
return `Status: CLOSED ${cid.map(item => `${item[0]}: $${item[1].toFixed(2)}`).join(" ")}`;
}
for (const currency of CURRENCY_UNITS) {
const currencyName = currency.name;
const currencyValue = currency.value;
let available = cid.find(item => item[0] === currencyName)?.[1] || 0;
let amountToReturn = 0;
while (changeDue >= currencyValue && available >= currencyValue) {
changeDue -= currencyValue;
available -= currencyValue;
changeDue = Number(changeDue.toFixed(2));
amountToReturn += currencyValue;
}
if (amountToReturn > 0) {
changeArray.push(`${currencyName}: $${amountToReturn.toFixed(2)}`);
}
}
if (changeDue > 0) {
return "Status: INSUFFICIENT_FUNDS";
}
return `Status: OPEN ${changeArray.join(" ")}`;
}
// Event listener for purchase button
document.getElementById("purchase-btn").addEventListener("click", function () {
try {
price = safeParseInput("price");
const cash = safeParseInput("cash");
cid = [
["PENNY", safeParseInput("penny")],
["NICKEL", safeParseInput("nickel")],
["DIME", safeParseInput("dime")],
["QUARTER", safeParseInput("quarter")],
["ONE", safeParseInput("one")],
["FIVE", safeParseInput("five")],
["TEN", safeParseInput("ten")],
["TWENTY", safeParseInput("twenty")],
["ONE HUNDRED", safeParseInput("one-hundred")]
];
console.log("Parsed Inputs:", { price, cash, cid }); // Log parsed inputs for debugging
if (isNaN(price) || isNaN(cash) || cid.some(item => isNaN(item[1]))) {
alert("Please enter valid numerical values for all inputs.");
return;
}
if (cash < price) {
alert("Customer does not have enough money to purchase the item");
return;
}
if (cash === price) {
document.getElementById("change-due").textContent = "No change due - customer paid with exact cash";
return;
}
const result = calculateChange(price, cash, cid);
document.getElementById("change-due").textContent = result;
} catch (error) {
console.error("Error processing purchase:", error);
alert("An unexpected error occurred. Please check the inputs.");
}
});
// Initialize elements on load
initializeElements();
/* file: styles.css */
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36
Challenge Information:
Build a Cash Register Project - Build a Cash Register