Build a Cash Register Project - Build a Cash Register

Tell us what’s happening:

failed with these three test cases:
please help resolving

  1. 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”.

2)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.

  1. When price is less than the value in the #cash element, total cash in drawer cid is greater than the change due, individual denomination amounts allows for returning change due, and the #purchase-btn element is clicked, the value in the #change-due element should be “Status: OPEN” with required change due in coins and bills sorted in highest to lowest order.

Your code so far

<!-- file: index.html -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <link rel="stylesheet" href="styles.css"><title>CashRegisterProject</title></head>
  <body>
    <div align="center">
      <label >Enter Cash From Customer</label> 
      <input type = "text" placeholder="customer cash" id="cash" onfocus="onFocus()"/><br><br>
<button type="submit" id="purchase-btn">Purchase</button>
    </div>
    <div class="TotalChange" id="change-due">

      </div>
    <script src = "script.js">

    </script>
  </body>
</html>
/* file: script.js */
let price = 19.5;
let totalChange = 0;
let cid = [
 ["PENNY", 0.5], 
 ["NICKEL", 0], 
 ["DIME", 0], 
 ["QUARTER", 0], 
 ["ONE", 0], 
 ["FIVE", 0], 
 ["TEN", 0], 
 ["TWENTY", 0], 
 ["ONE HUNDRED", 0]];

const customerCash = document.getElementById("cash");
const purchase = document.getElementById("purchase-btn");
const change = document.getElementById("change-due");
//const drawerChange = document.getElementById("DrawerChange");

let changeArr = [];


function onFocus(){
  customerCash.value = "";
  change.textContent = "";
  changeArr = [];
  totalChange = 0;
  //drawerChange.textContent = "";
}

purchase.addEventListener("click",()=>{
  let cash = customerCash.value;
 // console.log("cash:",cash);
 // console.log("price:",price);
      let currencyUnit = [
        ["PENNY", 0.01],
        ["NICKEL", 0.05],
        ["DIME", 0.10],
        ["QUARTER", 0.25],
        ["ONE", 1.00],
        ["FIVE", 5.00],
        ["TEN", 10.00],
        ["TWENTY", 20.00],
        ["ONE HUNDRED", 100.00]
    ];

  // create change string array
const createChangeString = () => {
  let changeString = '';
  
  for(let i=0;i<changeArr.length;i++){
    if(changeArr[i][1]>0){
      changeString += `${changeArr[i][0]}: $${changeArr[i][1]} `;
      
    }
  }
  console.log(`Change string ${changeString}` );
  /*ac.toReversed().map(object => {
    if(object.giveChange > 0) {
      changeString += `${object.name}: $${object.giveChange} `
    }
  })*/
  return changeString;
}

function getTotalValue(cid) {
    return cid.reduce((total, [unit, amount]) => total + amount, 0);
}

  if(cash > price){
    totalChange = cash-price;
    //const originalChange = totalChange;
    // Test the function
    let totalCID = getTotalValue(cid);
    console.log(`Total value in cash drawer: $${totalCID.toFixed(2)} , Total change to be given: ${totalChange.toFixed(2)}`);


    if (totalCID < change) {
      change.textContent ="Status: INSUFFICIENT_FUNDS";
    }else if (totalCID == change){
    change.textContent ="Status: CLOSED"
    }else {
      cid = cid.reverse();
      //cid = cid.sort((a, b) => b[1] - a[1]);
      //currencyUnit = currencyUnit.sort((a,b) => b[1]-a[1]);
      currencyUnit = currencyUnit.reverse();
      console.log("CID",cid);
        
        let coinName="";
        let coinValue=0;
        let coinsToReturn = 0;
      for (let i = 0; i < currencyUnit.length; i++) {
        if(totalChange != 0){
        console.log ('The :', cid[i][0])
        coinName = currencyUnit[i][0];
        coinValue = currencyUnit[i][1];
        let coinTotal = cid[i][1];
        let coinAmount = (coinTotal / coinValue).toFixed(2);
        
        console.log(`coinName: ${coinName} , coinValue: ${coinValue} ,coinTotal: ${coinTotal} , coinAmount: ${coinAmount}`);

        while (totalChange >= coinValue && coinTotal > 0) {
          console.log (' while loop for:', cid[i][0])
            totalChange -= coinValue;
            totalChange = totalChange.toFixed(2); 
            coinTotal -= coinValue;
            //TODO:Redue the CID array value
            coinsToReturn++;
            totalCID -= totalChange;
            //totalCID = totalCID.toFixed(2);
            console.log(`inside while totalChange: ${totalChange}, coins to return: ${coinsToReturn}`);
        }
      

console.log(`outside while totalChange: ${totalChange}, coins to return: ${coinsToReturn} total cash left in drawer: ${totalCID.toFixed(2)}`);

        if (coinsToReturn > 0) {
            changeArr.push([coinName, coinsToReturn * coinValue.toFixed(2)]);
            //changeArr.sort((a,b) => b[1]-a[1]);
            
        }
      coinsToReturn = 0;
        }}
  //changeArr = changeArr.sort((a, b) => b[1] - a[1])
  console.log(`changeArr: ${changeArr}`);
        // If the remaining change is not 0, it means we couldn't provide the exact change
      if (totalChange > 0) {
          change.textContent = "Status: INSUFFICIENT_FUNDS";
      } else {
        if(totalCID.toFixed(2)>0.00){
          change.textContent = "Status: OPEN " + createChangeString().trim();}
          else{
            console.log("totalCashInDrawer is zero,else block entered")
            change.textContent = "Status: CLOSED " + createChangeString().trim();}
          }

      }
    }

  
  else if(cash == price){
    change.textContent = "No change due - customer paid with exact cash";
  }
  else{
    alert("Customer does not have enough money to purchase the item");
  }

});

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

Challenge Information:

Build a Cash Register Project - Build a Cash Register

Blockquote

Have you tried testing with the values in the testcase yet?
What debugging did you try to help you identify the issue?

  1. yes, tested with the values in test case… i am globally using it to test each case. or just run the testcases, so it checks with the inbuild script.

2)used console logs to debug.
in the first failed test case:

  1. 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”
    i get the exact same output but still it fails.

other two. i did sort my array from highest to lowest. but it still fails. need help.
i am stuck here for more than 3 days.

1 Like

This is one place that may cause a problem.
The tests are automated so this event will never trigger.
Try to make these resets (specifically the changeArr and totalChange and maybe even the change.textContent) happen every time the purchase click event is triggered in addition just to make sure the testing method triggers it too.

Thank you… you are right. since test cases are automated those lines will not get hit. so, moved it into purchase button click event.
it resolved two among three failing test cases.

still one fails:
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.

i did add code to sort the final changeArr before printing. please help.

purchase.addEventListener("click",()=>{
  let cash = customerCash.value;
  changeArr = [];
  totalChange = 0;
  change.textContent = "";
  
 // console.log("cash:",cash);
 // console.log("price:",price);
      let currencyUnit = [
        ["PENNY", 0.01],
        ["NICKEL", 0.05],
        ["DIME", 0.10],
        ["QUARTER", 0.25],
        ["ONE", 1.00],
        ["FIVE", 5.00],
        ["TEN", 10.00],
        ["TWENTY", 20.00],
        ["ONE HUNDRED", 100.00]
    ];

  // create change string array
const createChangeString = () => {
  let changeString = '';
  
  for(let i=0;i<changeArr.length;i++){
    if(changeArr[i][1]>0){
      changeString += `${changeArr[i][0]}: $${changeArr[i][1]} `;
      
    }
  }
  console.log(`Change string ${changeString}` );
  /*ac.toReversed().map(object => {
    if(object.giveChange > 0) {
      changeString += `${object.name}: $${object.giveChange} `
    }
  })*/
  return changeString;
}

function getTotalValue(cid) {
    return cid.reduce((total, [unit, amount]) => total + amount, 0);
}

  if(cash > price){
    totalChange = cash-price;
    //const originalChange = totalChange;
    // Test the function
    let totalCID = getTotalValue(cid);
    console.log(`Total value in cash drawer: $${totalCID.toFixed(2)} , Total change to be given: ${totalChange.toFixed(2)}`);


    
    if(totalCID >= totalChange) {
      cid = cid.reverse();
      //cid = cid.sort((a, b) => b[1] - a[1]);
      //currencyUnit = currencyUnit.sort((a,b) => b[1]-a[1]);
      currencyUnit = currencyUnit.reverse();
      console.log("CID",cid);
        
        let coinName="";
        let coinValue=0;
        let coinsToReturn = 0;
      for (let i = 0; i < currencyUnit.length; i++) {
        if(totalChange != 0){
        console.log ('The :', cid[i][0])
        coinName = currencyUnit[i][0];
        coinValue = currencyUnit[i][1];
        let coinTotal = cid[i][1];
        let coinAmount = (coinTotal / coinValue).toFixed(2);
        
        console.log(`coinName: ${coinName} , coinValue: ${coinValue} ,coinTotal: ${coinTotal} , coinAmount: ${coinAmount}`);

        while (totalChange >= coinValue && coinTotal > 0) {
          console.log (' while loop for:', cid[i][0])
            totalChange -= coinValue;
            totalChange = totalChange.toFixed(2); 
            coinTotal -= coinValue;
            //TODO:Redue the CID array value
            coinsToReturn++;
            totalCID -= totalChange;
            //totalCID = totalCID.toFixed(2);
            console.log(`inside while totalChange: ${totalChange}, coins to return: ${coinsToReturn}`);
        }
      

console.log(`outside while totalChange: ${totalChange}, coins to return: ${coinsToReturn} total cash left in drawer: ${totalCID.toFixed(2)}`);

        if (coinsToReturn > 0) {
            changeArr.push([coinName, coinsToReturn * coinValue.toFixed(2)]);
            //changeArr.sort((a,b) => b[1]-a[1]);
            
        }
      coinsToReturn = 0;
        }}
  changeArr = changeArr.sort((a, b) => b[1] - a[1])
  console.log(`changeArr: ${changeArr}`);
        // If the remaining change is not 0, it means we couldn't provide the exact change
      if (totalChange > 0) {
          change.textContent = "Status: INSUFFICIENT_FUNDS";
      } else {
        if(totalCID.toFixed(2)>0.00){
          change.textContent = "Status: OPEN " + createChangeString().trim();}
          else{
            console.log("totalCashInDrawer is zero,else block entered")
            change.textContent = "Status: CLOSED " + createChangeString().trim();}
          }

      }
      /*else if (totalCID == totalChange){
    change.textContent ="Status: CLOSED "+ createChangeString().trim();
    }*/
    else {
      change.textContent ="Status: INSUFFICIENT_FUNDS";
    }}

when I was testing your code earlier, I noticed some weird behaviour.

At that point with price = 19.5 in the code, I typed in a large number (greater than the cash available). This triggered your INSUFFICIENT_FUNDS return which I expected to happen.
However, I then typed in a small amount like 19.6 which is supposed to give me ten cents in change, but your code stayed on INSUFFICIENT_FUNDS returned.

Can you try this test and see if it happens with your new code?
If it does, try to debug.
If you need help, please re-share your full code again.

thank you for your help. fixed it and the test passed.
both the above comments helped me fix the issue.
thank you

1 Like