Build a Cash Register Project - Build a Cash Register

Tell us what’s happening:

My code, despite presenting all the same items as the console, does not pass items 13 to 19? Can anyone help me?

Your code so far

<!DOCTYPE html>  
<html lang="en">  
  <head>  
    <meta charset="UTF-8" />  
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />  
    <meta name="viewport" content="width=device-width, initial-scale=1.0" /> 
    <title>Cash Register Project</title>  
    <style>  
body {  
    display: flex;  
    flex-direction: column;   
    align-items: center;   
    padding: 10px;  
    font-family: Arial, sans-serif; 
    background-color: #f4f4f4;  
}  

#input, #due, #remaining {  
    background-color: #e7f3fe;   
    padding: 10px; 
    border-radius: 8px;  
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);  
    width: 300px;
    margin: 10px;  
}     
#due {  
    background-color: #ffcccb;
}    
#remaining {  
    background-color: yellow;
}  
        }             
    </style>  
  </head>  
  <body>  
    <div id="input">
      <p>Cash Register Project</p>  
      <p>Price: <span id="price"></span></p>     
      <label>Enter cash from customer:</label><br/>  
      <input type="number" id="cash" /> 
      <button id="purchase-btn">Purchase</button>     
    </div>
    <div id="due">
      <p>The amount of money that should be refunded to the customer.</p>
      <div id="change-due"></div> 
    </div>
    <div id="remaining">
      <p>Change in drawer:</p>
      <div id="remainingMoney"></div> 
    </div>
     <div id="output2"></div>
     <div id="output3"></div>
    <script src="script.js"></script>  
  </body>  
</html>  
let price = 3.26;
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 rate = [.01,0.050,.1,.25,1,5,10,20,100];
let cid2 = [  
  ['PENNY'      , cid[0][1], Math.round(cid[0][1]/rate[0])],  
  ['NICKEL'     , cid[1][1], Math.round(cid[1][1]/rate[1])],  
  ['DIME'       , cid[2][1], Math.round(cid[2][1]/rate[2])],  
  ['QUARTER'    , cid[3][1], Math.round(cid[3][1]/rate[3])],  
  ['ONE'        , cid[4][1], Math.round(cid[4][1]/rate[4])],  
  ['FIVE'       , cid[5][1], Math.round(cid[5][1]/rate[5])],  
  ['TEN'        , cid[6][1], Math.round(cid[6][1]/rate[6])],  
  ['TWENTY'     , cid[7][1], Math.round(cid[7][1]/rate[7])],  
  ['ONE HUNDRED', cid[8][1], Math.round(cid[8][1]/rate[8])]  
];  

const purchaseBtn = document.getElementById("purchase-btn");             
const price2 = document.getElementById("price");  
price2.textContent = price;
let total = 0;

purchaseBtn.addEventListener("click", () => {

  const changeDue = document.getElementById("change-due");
  const remainingMoney = document.getElementById("remainingMoney")
  const outPut2 = document.getElementById("output2");  
  const outPut3 = document.getElementById("output3");   

  
  changeDue.innerHTML = "";
  outPut2.innerHTML = "";
  outPut3.innerHTML = "";
  remainingMoney.innerHTML = "";
  let passDadan = [  ['PENNY'      , 0, .01],  
                     ['NICKEL'     , 0, .05],  
                     ['DIME'       , 0, .1 ],  
                     ['QUARTER'    , 0, .25],  
                     ['ONE'        , 0, 1  ],  
                     ['FIVE'       , 0, 5  ],  
                     ['TEN'        , 0, 10 ],  
                     ['TWENTY'     , 0, 20 ],  
                     ['ONE HUNDRED', 0, 100] ];

  const total = cid2.reduce((acc, current) => acc + current[1],0);
  const cash = parseFloat(document.getElementById("cash").value);

  if (cash < price) {
    alert("Customer does not have enough money to purchase the item");
  } else if (cash === price) {
    changeDue.innerHTML = "No change due - customer paid with exact cash";
    return; 
  } else { 
    let result = calculate(cash, price, cid2, passDadan);
    cid2 = result.cid2;
    passDadan = result.passDadan;

    if (!result.trueOrFalse) {  
        if (price + total == cash) {
            changeDue.innerHTML = "CLOSED";
            passDadan.reverse().forEach((item) => { 
                if (item[1] > 0) {
                    changeDue.innerHTML += `  
                <p>${item[0]}:<span> $${(item[1]*item[2]).toFixed(2)}</span></p>  
                `;  
                }  
            });

            cid2.forEach((item) => { 
                remainingMoney.innerHTML += `  
            <p>${item[0]}:<span> $${item[1].toFixed(2)}</span></p>  
            `;   
            });
            return;
        } else {
            changeDue.innerHTML = "Status: OPEN"
            passDadan.reverse().forEach((item) => {
            if (item[1] > 0) {
                changeDue.innerHTML += `
            <p>${item[0]}:<span> $${(item[1]*item[2]).toFixed(2)}</span></p>  
            `;
            } 
            });
            cid2.forEach((item) => { 
                remainingMoney.innerHTML += `  
            <p>${item[0]}:<span> $${item[1].toFixed(2)}</span></p>  
            `;   
            });
            return;            
        }
    } else {  
        changeDue.innerHTML = "Status: INSUFFICIENT_FUNDS";
        cid2.forEach((item) => { 
                remainingMoney.innerHTML += `  
            <p>${item[0]}:<span> $${item[1].toFixed(2)}</span></p>  
            `;   
            });
        return;   
    }
  }

function calculate(cash, price, cid2, passDadan) {
const money = [0.01, 0.05, 0.1, 0.25, 1, 5, 10, 20, 100];
let reduce = parseFloat((cash - price).toFixed(2));
let totalPaid = 0;
let cid2Copy = JSON.parse(JSON.stringify(cid2)); 
let passDadanCopy = JSON.parse(JSON.stringify(passDadan)); 

for (let i = 8; i >= 0; i--) {
    while (reduce >= money[i] && cid2Copy[i][2] > 0) {
        reduce = parseFloat((reduce - money[i]).toFixed(2));
        cid2Copy[i][2] -= 1;
        cid2Copy[i][1] -= money[i];
        passDadanCopy[i][1] += 1;
    }
    totalPaid += passDadanCopy[i][1] * money[i];

    if (Math.abs(totalPaid - (cash - price)) < 0.001) {
        return { trueOrFalse: false, cid2: cid2Copy, passDadan: passDadanCopy };
    }
}
return { trueOrFalse: true, cid2: cid2, passDadan: passDadan };
}
})

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

Challenge Information:

Build a Cash Register Project - Build a Cash Register
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures-v8/build-a-cash-register-project/build-a-cash-register`Preformatted text`

You shouldn’t have mutable global variables like this

What’s wrong with it? It’s giving the right answer!!

didn’t you just say your code doesn’t pass the tests?

You can paste the code here below your code: cash register test suite.js · GitHub
it does to your app what the tests do, and you can debug with that, and find out why that global variable is a bad idea

1 Like

What happens to that variable if cid is changed?

If cid changes, the variable cid2 also changes

Thanks. I will tray.

Why? Where does cid2 get changed?

I don’t understand what you mean. The answer to this question is obvious, as shown by the following code.

let cid2 = [  
  ['PENNY'      , cid[0][1], Math.round(cid[0][1]/rate[0])],  
  ['NICKEL'     , cid[1][1], Math.round(cid[1][1]/rate[1])],  
  ['DIME'       , cid[2][1], Math.round(cid[2][1]/rate[2])],  
  ['QUARTER'    , cid[3][1], Math.round(cid[3][1]/rate[3])],  
  ['ONE'        , cid[4][1], Math.round(cid[4][1]/rate[4])],  
  ['FIVE'       , cid[5][1], Math.round(cid[5][1]/rate[5])],  
  ['TEN'        , cid[6][1], Math.round(cid[6][1]/rate[6])],  
  ['TWENTY'     , cid[7][1], Math.round(cid[7][1]/rate[7])],  
  ['ONE HUNDRED', cid[8][1], Math.round(cid[8][1]/rate[8])]  
];  

Nope, that is where the cid2 variable is first declared. If cid itself gets changed after the script is loaded, when does cid2 get changed?

Everywhere cid2 changes, and to avoid the previous issue, I have taken a copy of it before running my function.

let cid2Copy = JSON.parse(JSON.stringify(cid2)); 
let passDadanCopy = JSON.parse(JSON.stringify(passDadan)); ```

You’re missing the point. cid2 doesn’t change. That fundamentally breaks your code.

To fix this, you should ditch all of your extra global variables that are not price, cid, or any DOM elements.

I understand. Thank you.

Thank you very much for your guidance. You helped me a lot, and I learned many new points.

1 Like