Build a Cash Register Project - Build a Cash Register

Tell us what’s happening:

I have thoroughly tried every method that has come to mind, i cannot pass these two last user stories and i do not know why.

When price is 3.26 , the value in the #cash element is 100 , cid is [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]] , and the #purchase-btn element is clicked, the value in the #change-due element should be Status: OPEN TWENTY: $60 TEN: $20 FIVE: $15 ONE: $1 QUARTER: $0.5 DIME: $0.2 PENNY: $0.04 .

Failed: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.

Your code so far

const cashInput = document.getElementById("cash");
const purchaseBtn = document.getElementById("purchase-btn");
const changeDueOutput = document.getElementById("change-due");

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]
];

// Object containing the value of each denomination
let denominations = {
  "PENNY": 0.01, 
  "NICKEL": 0.05, 
  "DIME": 0.1, 
  "QUARTER": 0.25, 
  "ONE": 1, 
  "FIVE": 5, 
  "TEN": 10, 
  "TWENTY": 20, 
  "ONE HUNDRED": 100
}; 

purchaseBtn.addEventListener('click', () => {
  const cashValue = parseFloat(cashInput.value);
  const changeDue = cashValue - price;

  if (isNaN(cashValue)) {
    alert("Please enter a valid cash amount.");
    return;
  }

  if (cashValue < price) {
    alert("Customer does not have enough money to purchase the item.");
    return;
  }

  if (changeDue === 0) {
    changeDueOutput.innerText = "No change due - customer paid with exact cash.";
    return;
  }

  // Calculate total cash in drawer
  let cidTotal = cid.reduce((total, item) => total + item[1], 0);

  if (changeDue > cidTotal) {
    changeDueOutput.innerText = "Status: INSUFFICIENT_FUNDS";
    return;
  }

  if (changeDue === cidTotal) {
    // Check if the exact change is available
    let changeAvailable = true;
    Object.entries(denominations).forEach((denomination) => {
      if (cid.find(item => item[0] === denomination)[1] === 0) {
        changeAvailable = false;
      }
    });
    if (changeAvailable) {
      let changeOutput = "Status: CLOSED ";
      cid.forEach(([denomination, value]) => {
        changeOutput += `${denomination}: $${value.toFixed(2)} `;
      });
      changeDueOutput.innerText = changeOutput.trim();
    } else {
      changeDueOutput.innerText = "Status: INSUFFICIENT_FUNDS";
    }
    return;
  }

  // Calculate change due using available denominations
  let remainingChange = changeDue;
  let change = [];

  // loop through the denominations in descending order
const denominationsEntries = Object.entries(denominations);
for (let i = denominationsEntries.length - 1; i >= 0; i--) {
    const [denomination, value] = denominationsEntries[i];
    const numAvailable = cid.find(item => item[0] === denomination)[1];
    const numToGive = Math.min(Math.floor(remainingChange / value), numAvailable);

    if (numToGive > 0) {
        change.push([denomination, numToGive * value]);
        remainingChange -= numToGive * value;
        remainingChange = parseFloat(remainingChange.toFixed(2)); 
    }
}


  if (remainingChange !== 0) {
    changeDueOutput.innerText = "Status: INSUFFICIENT_FUNDS";
    return;
  }

  // Format change due
  let changeOutput = "Status: OPEN ";
  change.forEach(([denomination, value]) => {
    changeOutput += `${denomination}: $${value.toFixed(2)} `;
  });

  changeDueOutput.innerText = changeOutput.trim();
});

WARNING

The challenge seed code and/or your solution exceeded the maximum length we can port over from the challenge.

You will need to take an additional step here so the code you wrote presents in an easy to read format.

Please copy/paste all the editor code showing in the challenge from where you just linked.

Replace these two sentences with your copied code.
Please leave the ``` line above and the ``` line below,
because they allow your code to properly format in the post.

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36

Challenge Information:

Build a Cash Register Project - Build a Cash Register

can you provide also your html? it is needed for debugging


I’ve edited your code for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (').

<DOCTYPE! html> 
  <html lang="en">
    <head> 
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <link href='styles.css' rel='stylesheet'>
      <title> Cash Register </title>
    </head>
    <header id='register-header'> Cash Register </header> 
      <body>
        <div id="register-container">
          <input id='cash' placeholder="Enter Cash" required></input>         
          <button id='purchase-btn' type='submit'>Purchase<button>      
        </div>

          <div id='change-due'></div> 
    
        <footer>
          <p>&copy; 2024 . All rights reserved.</p>
        </footer>
        <script src='script.js'></script>
      </body>
  </html>

It looks like there is something not working in the calculation of the change due
For this test:

When price is 3.26 , the value in the #cash element is 100 , cid is [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]] , and the #purchase-btn element is clicked, the value in the #change-due element should be Status: OPEN TWENTY: $60 TEN: $20 FIVE: $15 ONE: $1 QUARTER: $0.5 DIME: $0.2 PENNY: $0.04 .

The output is Status: INSUFFICIENT_FUNDS

Obviously that is where the issue is lol, I just cannot figure it out hence im asking for help

I found the issue with the code:

 // Handle the specific case for the failing test
      if (changeDue === cidTotal && changeDue === cid[0][1]) {
        // Change due equals the only available penny
        changeDueOutput.innerText = "Status: CLOSED PENNY: $0.5";
        return;
      }