Build a Cash Register Project - Build a Cash Register - Final Test Case

Tell us what’s happening:

My code is failing the last test, When I enter the cid and price manually I’m getting the same results as the test case. I think the issue might be from the penultimate test case.

When I try looking through the console when the test has been run it looks as if the last test hasn’t even been run, which leads me to believe that the previous test is causing the final one not to pass, should I just rewrite the whole script at this stage?

I have tried reformating it multiple times because my previous attempt created an infinite loop.

Any pointers would be greatly appreciated :pray::pray::pray:

Your code so far

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.

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

JavaScript

let price = 19.5;
let cid = [["PENNY", 0.01], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 1], ["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 originalCid = cid.slice();

// 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";
    cid = originalCid;
    console.log(cid);
    updateCidDisplay();
  }
  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)
  } 

}
console.log("!!!!!!NEW TEST!!!!");
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 (iterations > 9 && cidHighToLowCents[unit][1] === 0){
     changeAvailable = false; 
   }
   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 = Math.floor(changeCents /currencyUnitsInCentsHighToLow[unit][1])

  console.log("amount of coints to add variable")
  console.log(ammountOfCoinsToAdd)
  
     while (changeCents >= currencyUnitsInCentsHighToLow[unit][1] && cidHighToLowCents[unit][1] !== 0){
       console.log(changeCents, " = changeCents");
      console.log("inner while loop has started");
      detailedChangeArr.push((currencyUnitsInCentsHighToLow[unit])); 
      console.log("currencyUnit = " + currencyUnitsInCentsHighToLow[unit])
      
      cidHighToLowCents[unit][1] -= currencyUnitsInCentsHighToLow[unit][1];
      
      changeCents -= 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]);
     
     
     
     
     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;
    console.log(change, "change at the end of change function")
    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;
      changeDueOutput.innerText = "Status: INSUFFICIENT_FUNDS";
    cid = originalCid;
    changeDenominationsArr = [];
    console.log(cid);
    updateCidDisplay();
    }
    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

you have a few things as global variables, the tests run the code multiple times in sequence changing cid and price, the other global variables are not reset to their starting state, you may want to consider that

1 Like

Thank you so much :tada::tada::tada: