Build a Cash Register Project - Build a Cash Register

Tell us what’s happening:

I have been working on this for a solid week, when I change the cid the results of the tests are different - could this be a bug? Even with that said it never passes all tests.

I think the issue stems from the while loop creating an infinite loop, is there any pointers please that can help me get past this project. I’m getting very frustrated with it and want to move on.

Many thanks in advance :crossed_fingers::pray:

Ollie

Your code so far

function changeFunction(change){
  console.log("*  Change function has been called")


  const currencyUnitsInCentsHighToLow = currencyUnitsInCents.slice().reverse();
  const detailedChangeArr = [];
  let cidHighToLowCents = cidCents.slice().reverse();
  let changeCents = change * 100;

  console.log("change in cents = " + changeCents);
  changeDueOutput.innerText = "$" + change;


 while(changeCents > 0 && changeAvailable === true) {
   for (let unit in currencyUnitsInCentsHighToLow){
   console.log(unit);
   if (
     currencyUnitsInCentsHighToLow[unit][1] <= changeCents 
   
   && cidHighToLowCents[unit][1] >= currencyUnitsInCentsHighToLow[unit][1]  
   ) {
     
     console.log(cidHighToLowCents[unit][1] + " " + currencyUnitsInCentsHighToLow[unit][1] )
     console.log("Item to be added to detailed change array is " + currencyUnitsInCentsHighToLow[unit])

    
     detailedChangeArr.push((currencyUnitsInCentsHighToLow[unit]));
     console.log()
     console.log("Detailed Change Arr is below:")
     console.log(detailedChangeArr);
     console.log();

     
     console.log(changeCents + "  = change in cents, begining of loop");
    
     cidHighToLowCents[unit][1] -= currencyUnitsInCentsHighToLow[unit][1]

     console.log("currentCid Unit is " + cidHighToLowCents[unit]);
     
     
     changeCents -= currencyUnitsInCentsHighToLow[unit][1];
     
     console.log("Change is of type \n" + typeof change)
     console.log(changeCents + " change in cents after");
     console.log(changeAvailable);
     break;
    } else {
      console.log("!! - End of the for in loop iteration")
      
    } 
   } 
   
 }console.log("!! - Out of while loop")

    change = changeCents / 100;
    cid = cidHighToLowCents.slice().map((([denomination, value]) => [denomination, value / 100])).reverse();
    let changeDenominationsArr = sumChange(detailedChangeArr);
    changeDenominationsArr = centsToDollars(changeDenominationsArr);

    const totalOfCid = getCIDTotal(cid)
    console.log("change Denominations Array")
    console.log(changeDenominationsArr);
    console.log(totalOfCid);
    
    
    if (totalOfCid === change){
      changeDueOutput.innerHTML = `Status: CLOSED ${updateChangeArr(changeDenominationsArr)}`;
    } else if (change !== 0) {
      changeAvailable = false;
       checkCash();
    }
    else {
            changeDueOutput.innerHTML = `Status: OPEN ${updateChangeArr(changeDenominationsArr)}`;
      }

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.

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

let changeAvailable = true;

const currencyUnits = [
  ["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]
];

const currencyUnitsInCents = currencyUnits.map(([denomination, value]) => [denomination, value * 100]);
const cidCents = cid.map(([denomination, value]) => [denomination, value * 100]);

const cashInput = document.getElementById("cash");
const purchaseBtn = document.getElementById("purchase-btn");
const priceSpan = document.getElementById("price-span");
const changeDueOutput = document.getElementById("change-due");
const changeAvailableDisplay = document.getElementById("change-available-display");

purchaseBtn.addEventListener("click", checkCash)

priceSpan.innerText = `The price is $${price.toFixed(2)}`;

console.log("Currency Units in Cents:");
console.log(currencyUnitsInCents);
console.log();
console.log("CID in Cents:");
console.log(cidCents);
console.log();
console.log("CID:");
console.log(cid);
updateCidDisplay();


function getCIDTotal(cashInDraw){
  console.log("*  getCIDTotal function was called");
  
  let cidArray = [];

  for (let cash in cashInDraw) {
    cidArray.push(cashInDraw[cash][1]*100)
  };

  let cidTotal = cidArray.reduce((a, b) => a + b, 0) /100;

  console.log("total of CID" + "\n" + cidTotal+ "\n");
  
  return cidTotal > 0 ? parseFloat(cidTotal): 0;;
}

function checkCash(){
  console.log("*  check Cash function was called");
  
  const cashValue = parseFloat(cashInput.value);
  let change = parseFloat((cashValue - price));
  let cidTotal = getCIDTotal(cid);

  console.log(cashValue + " = cash value");
  console.log(price + "  = price"); 
  console.log(change + " = change value")

  if (change > cidTotal || changeAvailable === false){
    changeDueOutput.innerText = "Status: INSUFFICIENT_FUNDS";
  }
  else if (cashValue < price) {
    alert("Customer does not have enough money to purchase the item");
  }
  else if (cashValue === price){
    changeDueOutput.innerText = "No Change Due - customer paid with exact cash"
  }
  else if (cashValue >= price){
    changeFunction(change)
  } 

}

function changeFunction(change){
  console.log("*  Change function has been called")


  const currencyUnitsInCentsHighToLow = currencyUnitsInCents.slice().reverse();
  const detailedChangeArr = [];
  let cidHighToLowCents = cidCents.slice().reverse();
  let changeCents = change * 100;

  console.log("change in cents = " + changeCents);
  changeDueOutput.innerText = "$" + change;


 while(changeCents > 0 && changeAvailable === true) {
   for (let unit in currencyUnitsInCentsHighToLow){
   console.log(unit);
   if (
     currencyUnitsInCentsHighToLow[unit][1] <= changeCents 
   
   && cidHighToLowCents[unit][1] >= currencyUnitsInCentsHighToLow[unit][1]  
   ) {
     
     console.log(cidHighToLowCents[unit][1] + " " + currencyUnitsInCentsHighToLow[unit][1] )
     console.log("Item to be added to detailed change array is " + currencyUnitsInCentsHighToLow[unit])

    
     detailedChangeArr.push((currencyUnitsInCentsHighToLow[unit]));
     console.log()
     console.log("Detailed Change Arr is below:")
     console.log(detailedChangeArr);
     console.log();

     
     console.log(changeCents + "  = change in cents, begining of loop");
    
     cidHighToLowCents[unit][1] -= currencyUnitsInCentsHighToLow[unit][1]

     console.log("currentCid Unit is " + cidHighToLowCents[unit]);
     
     
     changeCents -= currencyUnitsInCentsHighToLow[unit][1];
     
     console.log("Change is of type \n" + typeof change)
     console.log(changeCents + " change in cents after");
     console.log(changeAvailable);
     break;
    } else {
      console.log("!! - End of the for in loop iteration")
      
    } 
   } 
   
 }console.log("!! - Out of while loop")

    change = changeCents / 100;
    cid = cidHighToLowCents.slice().map((([denomination, value]) => [denomination, value / 100])).reverse();
    let changeDenominationsArr = sumChange(detailedChangeArr);
    changeDenominationsArr = centsToDollars(changeDenominationsArr);

    const totalOfCid = getCIDTotal(cid)
    console.log("change Denominations Array")
    console.log(changeDenominationsArr);
    console.log(totalOfCid);
    
    
    if (totalOfCid === change){
      changeDueOutput.innerHTML = `Status: CLOSED ${updateChangeArr(changeDenominationsArr)}`;
    } else if (change !== 0) {
      changeAvailable = false;
       checkCash();
    }
    else {
            changeDueOutput.innerHTML = `Status: OPEN ${updateChangeArr(changeDenominationsArr)}`;
      }
  
 



function centsToDollars(changeArr) {
  
  return changeArr.map(([denomination, value])=>{
    return [denomination, value = (value / 100)]
  });
}

function sumChange(change) {
  console.log("sum change function was called");
  return change.reduce((result, [denomination, value]) => {
    const existingIndex = result.findIndex(([d]) => d === denomination);
    if (existingIndex !== -1) {
      result[existingIndex][1] += value;
    } else {
      result.push([denomination,  value]);
    }
    return result;
  }, []);
}

function updateChangeArr(changeArr) {
  let changeHTML = ``;
  changeArr.forEach(
         ([denomination, amount]) => {
           console.log
           ([denomination] + ": $" + [amount]);
           changeHTML += 
           ` <br> ${denomination}: $${amount}`;
         });
    return changeHTML}

       

}


function updateCidDisplay(){
  changeAvailableDisplay.innerHTML = 
  `<div class="change-available">Pennies: $${cid[0][1].toFixed(2)}
  <br>Nickles: $${cid[1][1]}
  <br>Dimes: $${cid[2][1]}
  <br>Quarters $${cid[3][1]}
  <br>Dollar Bills $${cid[4][1]}
  <br>Five Dollar Bills $${cid[5][1]}
  <br>Ten Dollar Bills $${cid[6][1]}
  <br>Twenty Dollar Bills $${cid[7][1]}
  <br>One Hundred Dollar Bills $${cid[8][1]}
  </div>`;
}

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36

Challenge Information:

Build a Cash Register Project - Build a Cash Register

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 (').

for proper debugging you will need to provide also the html, please

Thank you this is my first post in the forum💗

I have tried to edit the original post to add the HTML, however I cannot seem to find how to do that, so for now here is the HTML:

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

  <body>
    <main>
      <h1>Cash Register</h1>
      <span id="price-span"></span>
      <div id="change-due">
        here goes the change
      </div>
      <input id="cash">
      <button id="purchase-btn">Purchase</button>
      <div id="change-available-display"> Change Available:  
      </div>


    </main>
  <script src="./script.js"></script>
  </body>
</html>

from how the tests fail/pass, I would say your issue is that your functions rely on global variables that they shouldn’t rely on.

I have fixed the issue of the variables, however the last test case is still failing.

When I update the cid and price to be equal to the test case and enter the appropriate cash I get the correct answer, I have noticed that it is slow and goes through the loop 50 times to calculate the change.

Here is the updated code:

let price = 19.5;
let cid = [["PENNY", 0.5], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]];

let changeAvailable = true;

const currencyUnits = [
  ["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]
];

// const currencyUnitsInCents = currencyUnits.map(([denomination, value]) => [denomination, value * 100]);
// const cidCents = cid.map(([denomination, value]) => [denomination, value * 100]);

const cashInput = document.getElementById("cash");
const purchaseBtn = document.getElementById("purchase-btn");
const priceSpan = document.getElementById("price-span");
const changeDueOutput = document.getElementById("change-due");
const changeAvailableDisplay = document.getElementById("change-available-display");

purchaseBtn.addEventListener("click", checkCash)

priceSpan.innerText = `The price is $${price.toFixed(2)}`;

getCIDTotal(cid);
updateCidDisplay()

function getCIDTotal(cashInDraw){
  console.log("*  getCIDTotal function was called");
  
  let cidArray = [];

  for (let cash in cashInDraw) {
    cidArray.push(cashInDraw[cash][1]*100)
  };

  let cidTotal = cidArray.reduce((a, b) => a + b, 0) /100;

  console.log("total of CID" + "\n" + cidTotal+ "\n");
  
  return cidTotal > 0 ? parseFloat(cidTotal): 0;;
}

function checkCash(){
  console.log("*  check Cash function was called");
  
  const cashValue = parseFloat(cashInput.value);
  let change = parseFloat((cashValue - price));
  let cidTotal = getCIDTotal(cid);

  console.log(cashValue + " = cash value");
  console.log(price + "  = price"); 
  console.log(change + " = change value")

  if (change > cidTotal || changeAvailable === false){
    changeDueOutput.innerText = "Status: INSUFFICIENT_FUNDS";
  }
  else if (cashValue < price) {
    alert("Customer does not have enough money to purchase the item");
  }
  else if (cashValue === price){
    changeDueOutput.innerText = "No Change Due - customer paid with exact cash"
  }
  else if (cashValue >= price){
    changeFunction(change)
  } 

}

function changeFunction(change){
  console.log("*  Change function has been called")

  const currencyUnitsInCents = currencyUnits.map(([denomination, value]) => [denomination, value * 100]);
const cidCents = cid.map(([denomination, value]) => [denomination, value * 100]);
  const currencyUnitsInCentsHighToLow = currencyUnitsInCents.reverse().slice();
  const detailedChangeArr = [];
  let cidHighToLowCents = cidCents.reverse();
  let changeCents = change * 100;

  console.log("change in cents = " + changeCents);
  changeDueOutput.innerText = "$" + change;
  let iterations = 0;

 while(changeCents > 0 && changeAvailable === true) {
   
   iterations ++;
   
   for (let unit in currencyUnitsInCentsHighToLow){
   console.log(unit);
   if (
     currencyUnitsInCentsHighToLow[unit][1] <= changeCents 
   
   && cidHighToLowCents[unit][1] >= currencyUnitsInCentsHighToLow[unit][1] && cidHighToLowCents[unit][1] !== 0
   ) {
     
     console.log(cidHighToLowCents[unit][1] + " " + currencyUnitsInCentsHighToLow[unit][1] )
     console.log("Item to be added to detailed change array is " + currencyUnitsInCentsHighToLow[unit])
  
  let ammountOfCoinsToAdd = changeCents /currencyUnitsInCentsHighToLow[unit][1]
  console.log("amount of coints to add variable")
  console.log(ammountOfCoinsToAdd)
     
     detailedChangeArr.push((currencyUnitsInCentsHighToLow[unit])) ;
     
     cidHighToLowCents[unit][1] -= currencyUnitsInCentsHighToLow[unit][1]

     console.log()
     console.log("Detailed Change Arr is below:")
     console.log(detailedChangeArr);
     console.log();

     
     console.log(changeCents + "  = change in cents, begining of loop");
    
    //  cidHighToLowCents[unit][1] -= currencyUnitsInCentsHighToLow[unit][1]

     console.log("currentCid Unit is " + cidHighToLowCents[unit]);
     
     
     changeCents -= currencyUnitsInCentsHighToLow[unit][1];
     
     console.log("Change is of type \n" + typeof change)
     console.log(changeCents + " change in cents after");
     console.log(changeAvailable);
     break;
    } else {
      console.log("!! - End of the for in loop iteration")
      
    } 
   } 
   
 }console.log("!! - Out of while loop")

    change = changeCents / 100;
    cid = cidHighToLowCents.slice().map((([denomination, value]) => [denomination, value / 100])).reverse();
    let changeDenominationsArr = sumChange(detailedChangeArr);
    changeDenominationsArr = centsToDollars(changeDenominationsArr);


    updateCidDisplay()
    const totalOfCid = getCIDTotal(cid)
    console.log("change Denominations Array")
    console.log(changeDenominationsArr);
    console.log(totalOfCid);
    console.log(iterations + " = iterations");
    
    if (totalOfCid === change){
      changeDueOutput.innerHTML = `Status: CLOSED ${updateChangeArr(changeDenominationsArr)}`;
    } else if (change !== 0) {
      changeAvailable = false;
       checkCash();
    }
    else {
            changeDueOutput.innerHTML = `Status: OPEN ${updateChangeArr(changeDenominationsArr)}`;
      }
  
 



function centsToDollars(changeArr) {
  
  return changeArr.map(([denomination, value])=>{
    return [denomination, value = (value / 100)]
  });
}

function sumChange(change) {
  console.log("sum change function was called");
  return change.reduce((result, [denomination, value]) => {
    const existingIndex = result.findIndex(([d]) => d === denomination);
    if (existingIndex !== -1) {
      result[existingIndex][1] += value;
    } else {
      result.push([denomination,  value]);
    }
    return result;
  }, []);
}

function updateChangeArr(changeArr) {
  let changeHTML = ``;
  changeArr.forEach(
         ([denomination, amount]) => {
           console.log
           ([denomination] + ": $" + [amount]);
           changeHTML += 
           ` <br> ${denomination}: $${amount}`;
         });
    return changeHTML}

       

}


function updateCidDisplay(){
  changeAvailableDisplay.innerHTML = 
  `<div class="change-available">Pennies: $${cid[0][1].toFixed(2)}
  <br>Nickles: $${cid[1][1]}
  <br>Dimes: $${cid[2][1]}
  <br>Quarters $${cid[3][1]}
  <br>Dollar Bills $${cid[4][1]}
  <br>Five Dollar Bills $${cid[5][1]}
  <br>Ten Dollar Bills $${cid[6][1]}
  <br>Twenty Dollar Bills $${cid[7][1]}
  <br>One Hundred Dollar Bills $${cid[8][1]}
  </div>`;
}

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