Build a Cash Register Project - Build a Cash Register

Tell us what’s happening:

Good day everyone, I have some questions about this project. The code written is able to pass tests 1-12, but can’t pass the rest of them. The problem is that the result from my code seems to fit the description of the requirements. I guess the issue is about the textContent of the “changeDue” element, but I just can’t figure it out. Can anyone help me check what is happening with the code?

by the way i turn 2D array to Class to help myself easy to understand

Your code so far

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

/* file: script.js */
//認證數據
let price =19.5;
let cid = [["PENNY", 0.01], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]]



//get element
const cidElement = document.querySelector(".cid")
const pdPrice = document.querySelector("#price")
const customInput = document.querySelector("#cash")
const purchaseBtn = document.querySelector("#purchase-btn")
const changeDue = document.querySelector("#change-due")

//隨機價錢1-100 
let refoundArr = []



//建立收銀台
class ChangesInDraw{
    constructor(currencyUnit,amount,remain){
        this.currencyUnit = currencyUnit;
        this.amount = amount;
        this.remain = remain;
    }
}
let draw = [
    new ChangesInDraw(cid[8][0],100,cid[8][1]/100),
    new ChangesInDraw(cid[7][0],20,cid[7][1]/20),
    new ChangesInDraw(cid[6][0],10,cid[6][1]/10),
    new ChangesInDraw(cid[5][0],5,cid[5][1]/5),
    new ChangesInDraw(cid[4][0],1,cid[4][1]/1),
    new ChangesInDraw(cid[3][0],0.25,cid[3][1]/0.25),
    new ChangesInDraw(cid[2][0],0.1,cid[2][1]/0.1),
    new ChangesInDraw(cid[1][0],0.05,cid[1][1]/0.05),
    new ChangesInDraw(cid[0][0],0.01,cid[0][1]/0.01),
]




//功能
function findCashInDrawByAmount(unit){
    return draw.find(item=>item.amount === unit)
}
function renderDraw(draw){
    cidElement.innerHTML = `<h4>Cash in draw</h2>`
    draw.forEach((item) => {
        cidElement.innerHTML += `<span>${item.currencyUnit}</span><span id="remain">${item.remain}</span>`
    })
}

function renderChangeDue(cash,price){
    //重至
    changeDue.innerHTML = `<h3>Change-due status</h3>`
    //根據狀況顯示資訊
    if(cash < price){
        alert(`Customer does not have enough money to purchase the item`)
        changeDue.innerHTML = `<p>Customer does not have enough money to purchase the item</p>`
        return
    }
    else if(cash >= price){
        if(cash == price) {
            changeDue.innerHTML = `<p>No change due - customer paid with exact cash</p>`
            
            return
        }
        
        
        if(!doRefound(cash - price)){
            changeDue.textContent = `Status: INSUFFICIENT_FUNDS`
            return
        }
        else{
            if(draw.every(item => item.remain === 0)){
                
                changeDue.textContent = `Status: CLOSED`
                refoundArr.forEach(item => {
                if(item.amount){
                    changeDue.textContent += ` ${item.unitName.toUpperCase()}: \$${item.amount}`
                    return
                }
            })
            }
            else{changeDue.textContent = `Status: OPEN`
            refoundArr.forEach(item => {
                if(item.amount){
                    changeDue.textContent += ` ${item.unitName.toUpperCase()}: \$${item.amount}`
                    return
                }
            })}
            console.log(refoundArr)
        }
        return
    }
    
}

//演算
function doRefound(cash){
    let refound = cash
    refoundArr = []

    draw.forEach(unit => {
        let goingToTake = Math.floor(refound / unit.amount);
        let take = Math.min(goingToTake, unit.remain);
        refound = refound - take * unit.amount.toFixed(2);
        refound = refound.toFixed(2)

        refoundArr.push({unitName:unit.currencyUnit, amount: take*unit.amount.toFixed(2)})
        console.log(unit,refound,goingToTake)
    })

    console.log(refound)
    if(refound > 0){return false}
    else{
        refoundArr.forEach(item => {
           let tg =  draw.find(cid=>cid.currencyUnit === item.unitName)
           tg.remain = tg.remain - item.amount / tg.amount 
        })
        return refoundArr}
}



//渲染&監視
pdPrice.textContent = price
renderDraw(draw)
purchaseBtn.addEventListener('click', ()=>{
    console.log("got click")
    renderChangeDue(parseFloat(customInput.value), parseFloat(price))
    renderDraw(draw)
})

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

Challenge Information:

Build a Cash Register Project - Build a Cash Register

do not have extra variables in the global space, even if you reset it to empty array, it’s not good practice.

can you explain the logic of your code? so it is easier to debug

Variables: I pass data from a 2D array to a class to allow flexibility in changing the currency unit.

Functions:

  1. findCashInDrawByAmount()
    I’ll delete this function. It was initially intended to help find the currency, but I implemented a different logic that makes this unnecessary.
  2. renderDraw()
    This function updates the browser data when it needs to be refreshed.
  3. renderChangeDue(cash, price)
    This function updates the #changeDue section based on the situation of the drawer and the customer:
  • If the customer doesn’t have enough money, #changeDue will display “Customer does not have enough money to purchase the item,” and an alert will be shown.
  • If the cash equals the price, #changeDue will display “No change due - customer paid with exact cash.”
  • The function will call doRefund() to process any necessary refunds.
  • If doRefund() returns false, meaning the drawer doesn’t have enough cash to give the customer, #changeDue will display “Status: INSUFFICIENT_FUNDS.”
  • If there’s enough cash for an exact refund, #changeDue will display “Status: CLOSED” along with the details of which units and how many will be refunded (updated by doRefound()).
  • If the drawer has more than enough cash for the refund, #changeDue will display “Status: OPEN” along with refund details (updated by doRefound()).
  1. doRefound()
    This function checks if there is enough cash to give the customer change and updates the refoundArr with the specific units and quantities for the refund. If there isn’t enough cash for the refund, the function returns false to notify renderChangeDue() that the refund can’t be processed. If the refund is successful, it updates the status of the drawer.

where is your index.html file? Please post it.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Build a Cash Register</title>
    <link rel="stylesheet" href="./styles.css">
</head>
<body>
    <div class="container">
        <!-- 零錢狀況 -->
        <div class="cid">
            <h4>Cash in draw</h2>
        </div>
        <!-- 互動介面 -->
        <div class="interFace">
            <h2 id="title">Cash Register</h3>
            <input type="number" id="cash"  required>
            <button id="purchase-btn">purchase</button>
            <h3 class="price">Price: <span id="price"></span></h3>
        </div>
        <!-- 找零 -->
        <div id="change-due">
            <h3>Change-due status</h3>
        </div>
    </div>
    <script src="./script.js"></script>
</body>
</html>

note that you have code in the global scope that is causing a problem for the tests.
The only code that should be in the global scope is price and cid.
For example your let draw variable is in the global scope and will not pick up changes to the cid that the testcase will make after your code is loaded in.

I removed all variables in the global scope except for cid and price, and rewrote the code. The tests finally passed. Thank you for your advice!

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.