Build a Cash Register Project - Build a Cash Register

Tell us what’s happening:

I’ve tried so many different adjustments I’ve lost track, and I’m wavering between 3 - 5 criteria not being met. They often change based on what I put in for cid and price. I’ve utilized AI support, I’ve even tried to use the code from the example, and nothing’s doing.

Any ideas why I’m getting inconsistent results from my cid and price adjustments?

Your code so far

<!-- file: index.html -->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Cash Register Project</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <link href="./styles.css" rel="stylesheet">
</head>

<body>

<h1>Cash Register Project</h1>

<!-- cash input and output -->
<label for='cash'>Enter cash from customer:</label><br>
<input id="cash" type="number" step="0.01" min="0.00"><br>
<label for="change-due">Change Due:</label><br>
<div id="change-due"></div>
<button id="purchase-btn">Purchase</button>
    <script src="script.js"></script>
</body>

</html>
/* file: script.js */
// settings from FCC, don't change
let price = 19.5;

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

// imports from HTML
const cashInput = document.getElementById("cash");
const change = document.getElementById("change-due");
const payBtn = document.getElementById("purchase-btn");

// other needed variables
let montValues = [0.01, 0.05, 0.1, 0.25, 1, 5, 10, 20, 100];
let drawerStatus = true;
let changeArr = [];
let cidWithVal = [];

// Create a new array with monetary values added
const updateCWV = () => {
  cidWithVal = cid.map((item, index) => {
    const [unit, amount] = item; // Destructure the unit and amount
    const monetaryValue = montValues[index]; // Get the corresponding monetary value
    return [unit, amount, monetaryValue]; // Return the new array with the third value
  });
}

// Determine total cash in drawer
const totalCash = (arr) => {
  let cashSum = 0;
  for (let i = 0; i < arr.length; i++) {
    cashSum += arr[i][1]; // Use the passed array
  }
  return cashSum;
}

// Function to filter responses based on money given
const moneyCheck = (amt) => {
  let changeNeed = roundToTwoDecimals(amt - price);
  if (changeNeed < 0) {
    alert("Customer does not have enough money to purchase the item");
  } else if (changeNeed === 0) {
    change.textContent = "No change due - customer paid with exact cash";
  } else if (totalCash(cid) < changeNeed) {
    change.textContent = "Status: INSUFFICIENT_FUNDS";
  } else {
    makeChange(changeNeed);
  }
}

// Rounding function
const roundToTwoDecimals = (num) => {
  return Math.round(num * 100) / 100;
};

// Function to make change
const makeChange = (changeNeed) => {
  for (let i = cidWithVal.length - 1; i >= 0; i--) {
    const [unit, amount, value] = cidWithVal[i];
    // Check to see if the denomination amount is needed in giving change & you have some of that denom
    if (value <= changeNeed && amount > 0.00) {
      // If you need all of that denom value, you give it over, update change text, then change value to 0
      if (amount < changeNeed) {
        changeNeed = roundToTwoDecimals(changeNeed - amount);
        changeArr.push([unit, amount]);
        cidWithVal[i][1] = 0.00;
       // updateCWV();        
      } else {
        let denomAmt = Math.floor(changeNeed / value);
        changeNeed = roundToTwoDecimals(changeNeed - (denomAmt * value));
        changeArr.push([unit, (denomAmt * value)]);
        cidWithVal[i][1] -= denomAmt * value;
       // updateCWV();
      }
    }
  }
  if (changeNeed > 0) {
    change.textContent = "Status: INSUFFICIENT_FUNDS";
  } else { 
    printChange(changeArr);
  }
}

// Print change results
const printChange = (arr) => {
  // Check if drawer is open or closed
  drawerStatus = totalCash(cidWithVal) > 0;
  change.textContent = drawerStatus ? "Status: OPEN" : "Status: CLOSED";

  for (let i = 0; i < arr.length; i++) {
    change.textContent += ` ${arr[i][0]}: $${arr[i][1]}`;
  }
}

// When the button is clicked
updateCWV();
payBtn.addEventListener("click", () => {
  const adjCash = parseFloat(cashInput.value);
  moneyCheck(adjCash);
}); 
/* 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/132.0.0.0 Safari/537.36

Challenge Information:

Build a Cash Register Project - Build a Cash Register

These should not be global variables.

Your code contains global variables that are changed each time the function is run. This means that after each function call completes, subsequent function calls start with the previous value. To fix this, make sure your function doesn’t change any global variables, and declare/assign variables within the function if they need to be changed.

Example:

var myGlobal = [1];
function returnGlobal(arg) {
  myGlobal.push(arg);
  return myGlobal;
} // unreliable - array gets longer each time the function is run

function returnLocal(arg) {
  var myLocal = [1];
  myLocal.push(arg);
  return myLocal;
} // reliable - always returns an array of length 2

Thanks. So I see how that would make sense with the drawerStatus and changeArr variables. However, I’m still not sure what to do with the cidWithVal array. It’s referenced in multiple functions, so I feel like it should be global. I do feel like I haven’t set it up to update properly.

when the button is clicked the tests have given a new value to cid, but is your cidWithVal updated when the button is clicked?

It sounds like a variable that should be passed between functions. Ideally functions should only rely upon their inputs and only give data to other functions via their return value.

Thanks @JeremyLT and @ILM . I ended up solving it in steps. I changed all the cidWithVal array value references to cid, and then called the updateCWV function (took out the comments) at the end of each conditional. I also moved the updateCWV function call from outside the event listener to be the first thing inside of it. I might’ve done some other things I’m not remembering… but it worked! It’s still a global variable, so that might not be the best code, but it’s functioning! Thanks for your help.

Good work getting it passing. I would now try to clean up your code and get rid of that global variable.