Build a Cash Register Project - Build a Cash Register

Tell us what’s happening:

ISSUES WITH POINTS 18 AND 19, I CAN’T FIGURE OUT IF THERE IS A BUG OR NOT

Your code so far

<!-- file: index.html -->

/* file: script.js */

/* 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/133.0.0.0 Safari/537.36 Edg/133.0.0.0

Challenge Information:

Build a Cash Register Project - Build a Cash Register

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Cash Register</title>
</head>
<body>

  <h1>Cash Register System</h1>

  <p>Price of the item: $<span id="price">19.5</span></p>

  <label for="cash">Cash Provided: $</label>
  <input type="number" id="cash" step="0.01" required>

  <button id="purchase-btn">Make Purchase</button>

  <p id="change-due"></p>

  <div id="cid" style="display: none;">[["PENNY", 0.5], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]]</div>

  <script src="script.js"></script> 
</body>
</html>

// Definición global de las variables
let price = parseFloat(document.getElementById('price').innerText);  // Precio del artículo
let cid = JSON.parse(document.getElementById('cid').innerText); // Efectivo en caja

// Manejar el clic del botón de compra
document.getElementById('purchase-btn').addEventListener('click', function() {
    let cash = parseFloat(document.getElementById('cash').value);  // Dinero proporcionado por el cliente
    let changeDue = cash - price;  // Cambio que debe devolver el cajero

    // Condición 7 y 8: Si el dinero proporcionado es menor que el precio
    if (cash < price) {
        alert('Customer does not have enough money to purchase the item');
        document.getElementById('change-due').innerText = '';  // Vaciar el mensaje
        return;  // Salir de la función
    }

    // Condición 9 y 10: Si el dinero proporcionado es igual al precio
    if (cash === price) {
        document.getElementById('change-due').innerText = 'No change due - customer paid with exact cash';
        return;
    }

    // Condición 11: Si hay cambio debido y la cantidad en la caja es suficiente
    if (changeDue > 0) {
        let changeArr = calculateChange(changeDue, cid);  // Llamada a la función para calcular el cambio
        if (changeArr === 'INSUFFICIENT_FUNDS') {
            document.getElementById('change-due').innerText = 'Status: INSUFFICIENT_FUNDS';
        } else if (changeArr === 'CLOSED') {
            document.getElementById('change-due').innerText = 'Status: CLOSED';
        } else {
            let changeString = 'Status: OPEN ';
            changeArr.forEach(coin => {
                changeString += `${coin[0]}: $${coin[1].toFixed(2)} `;
            });
            document.getElementById('change-due').innerText = changeString;
        }
    }
});

// Función para calcular el cambio debido
function calculateChange(changeDue, cid) {
    let changeArr = [];
    let totalCid = 0;
    for (let i = 0; i < cid.length; i++) {
        totalCid += cid[i][1];
    }

    // Si el total en caja es menor que el cambio debido, no hay fondos suficientes
    if (totalCid < changeDue) {
        return 'INSUFFICIENT_FUNDS';
    }

    // Si el total en caja es igual al cambio debido, está cerrado
    if (totalCid === changeDue) {
        return 'CLOSED';
    }

    // Calcular el cambio exacto
    for (let i = cid.length - 1; i >= 0; i--) {
        let coinValue = getCoinValue(cid[i][0]);
        let coinAmount = cid[i][1];
        let coinCount = 0;

        while (changeDue >= coinValue && coinAmount > 0) {
            changeDue -= coinValue;
            coinAmount -= coinValue;
            coinCount++;
            changeDue = parseFloat(changeDue.toFixed(2));  // Para evitar problemas de precisión con los decimales
        }

        if (coinCount > 0) {
            changeArr.push([cid[i][0], coinCount * coinValue]);
        }
    }

    // Si después de calcular todo el cambio, aún hay dinero debido
    if (changeDue > 0) {
        return 'INSUFFICIENT_FUNDS';
    }

    return changeArr;
}

// Función para obtener el valor de cada tipo de moneda
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;
    }
}

there is no need to write all uppercase, it’s like yelling

these variables get a value directly, you don’t need to get it from the html

have you tested your app?
check what it returns for the conditions of this test

When price is 19.5 , the value in the #cash element is 20 , cid is [["PENNY", 0.5], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]] , and the #purchase-btn element is clicked, the value in the #change-due element should be "Status: CLOSED PENNY: $0.5" .

Sorry, I was in a hurry, but well, i did test it and this is the outcome: // running tests 18. When price is 19.5, the value in the #cash element is 20, cid is [["PENNY", 0.5], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]], and the #purchase-btn element is clicked, the value in the #change-due element should be "Status: CLOSED PENNY: $0.5". 19. When price is less than the value in the #cash element, total cash in drawer cid is equal to change due, and the #purchase-btn element is clicked, the value in the #change-due element should be "Status: CLOSED" with change due in coins and bills sorted in highest to lowest order. // tests completed

That is the test output, I mean you should try the app in the preview

1 Like

done, in the prewiev it works just fine, it starts telling me insufficient funds after 20, between 19.5 and 20 it tells me the amound of change, 19.5 says No change due - customer paid with exact cash and below that it gives me a pop up saying customer does not have enough money to purchase item, i really have no idea of whats going on :frowning:

where is the change due?

if you test your code like this for test 18:

console.log("\nTest #18");

price = 19.5;

document.querySelector('#cash').value = 20;

cid = [["PENNY", 0.5], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]];

document.querySelector('#purchase-btn').click();

console.log("actual", document.querySelector('#change-due').innerText);

console.log('expected', 'Status: CLOSED PENNY: $0.5')

this prints

Test #18
actual Status: CLOSED
expected Status: CLOSED PENNY: $0.5

you may notice what’s missing