Build a Cash Register Certification Project

Hey everyone,

I’m having trouble with my cash register project. When the change needed is equal to the total cash in drawer (CID), the status is reading “INSUFFICIENT_FUNDS” instead of “Status: CLOSED.”

I’ve checked the calcChange function and added conditions for when the total in the drawer equals the change, but I can’t figure out why it’s still showing the wrong status.

Here’s my code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="styles.css">
  </head>
  <body>
    <main class="register">
      <div id="total"></div>
      <div class="stands-container">
        <div class="stand"></div>
        <div class="stand"></div>
      </div>
      <div class="body">
        <section class="left-col">
          <p id="change-in-drawer">
            <strong>Change in Drawer: </strong></br>
          </p>
        </section>
        <section class="right-col">
          <input id="cash" type="number"></input>
          <button id="purchase-btn" type="button">Purchase</button>
          <p id="change-due">
            <strong>Change Due: </strong></br>
          </p>
        </section>
      </div>
      <div class="base">
        <div class="knob"></div>
      </div>
    </main>
    <script src="script.js"></script>
  </body>
</html>
let price = 19.5;
let currencyUnitsAndNotes = {}

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

const currencyUnits = {
  "PENNY": 0.01,
  "NICKEL": 0.05,
  "DIME": 0.1,
  "QUARTER": 0.25,
  "ONE": 1,
  "FIVE": 5,
  "TEN": 10,
  "TWENTY": 20,
  "ONE HUNDRED": 100
}

const changeLeftSpan = document.getElementById("change-in-drawer")
const cashInput = document.getElementById("cash")
const changeDue = document.getElementById("change-due")
const total = document.getElementById("total")
const purchaseBtn = document.getElementById("purchase-btn")

cid.forEach((unit) => {
  const unitValue = currencyUnits[unit[0]]
  currencyUnitsAndNotes[Number(currencyUnits[unit[0]])] = Math.ceil(unit[1]/unitValue)
})

total.innerText = `\$${price}`;
changeDue.innerHTML = `<strong> Change due: </strong>`

cid.forEach((item) => {
  changeLeftSpan.innerHTML +=
  `${item[0]}: \$${item[1]} </br>`
})

const sumDrawer = () => {
  let totalDrawerChange = 0;
  /*cid.forEach((item) => {
    totalDrawerChange += item[1]
  })*/
  let keys = Object.keys(currencyUnitsAndNotes)
  keys.forEach((key) => {
    totalDrawerChange += currencyUnitsAndNotes[key] * key
  })
  return totalDrawerChange
}

const findName = (num) => {
  let key = Object.keys(currencyUnits).find((e) => currencyUnits[e] === Number(num))
  return key
}

const updateUI = (noteGiven, amount) => {
  let noteToUpdate = cid.find((arr) => arr[0] === noteGiven)
  let updateIndex = cid.find((arr) => cid.indexOf(arr[0] === noteGiven))
  noteToUpdate[1] -= amount
  console.log(noteToUpdate[1])
  console.log(cid)
  changeLeftSpan.innerHTML = ""
  cid.forEach((e) => {
    changeLeftSpan.innerHTML +=
    `${e[0]}: \$${e[1]} </br>`
  })
}

const calcUnits = (change) => {
  change = parseFloat(change.toFixed(2))
  const listOfCurrencies = Object.keys(currencyUnitsAndNotes).sort((a,b) => a-b).reverse()
  let hasFoundChange = true

  while (change > 0) {
    change = parseFloat(change.toFixed(2))
    let changeToGive = listOfCurrencies.find((e) => change >= e && currencyUnitsAndNotes[e] > 0)
    let timesToGiveChange = Math.trunc(change / changeToGive)
    if (currencyUnitsAndNotes[changeToGive] < timesToGiveChange && currencyUnitsAndNotes[changeToGive] > 0) {
      let reversedArray = [...cid].reverse()
      console.log(reversedArray)
      let indexToFind = reversedArray.findIndex(e => e[0] === findName(changeToGive))
      console.log(indexToFind)
      let remainderArr = reversedArray.slice(indexToFind + 1)
      let sumRemainder = remainderArr.reduce((acc, el) => acc+el[1] , 0)
      if (sumRemainder < change && indexToFind < reversedArray.length - 1) {
        console.log(`Sum of remaining cash: ${sumRemainder}, Change needed: ${change}`);
        changeDue.innerText = `Status: INSUFFICIENT_FUNDS`
        break
      } else if (indexToFind === reversedArray.length-1) {
        if (reversedArray[indexToFind][1] < change) {
          console.log(`Sum of remaining cash: ${sumRemainder}, Change needed: ${change}`);
          changeDue.innerText = `Status: INSUFFICIENT_FUNDS`
          break
        }
      }
      console.log(`${findName(changeToGive)} (${changeToGive}) given ${(currencyUnitsAndNotes[changeToGive] * changeToGive).toFixed(2)} times`)
      changeDue.innerHTML += `${findName(changeToGive)}: \$${(currencyUnitsAndNotes[changeToGive] * changeToGive).toFixed(2)}</br>`
      change -= (changeToGive * currencyUnitsAndNotes[changeToGive]).toFixed(2)
      updateUI(findName(changeToGive), (changeToGive * currencyUnitsAndNotes[changeToGive]).toFixed(2))
      currencyUnitsAndNotes[changeToGive] = 0
    } else {
      let reversedArray = [...cid].reverse()
      console.log(reversedArray)
      let indexToFind = reversedArray.findIndex(e => e[0] === findName(changeToGive))
      console.log(indexToFind)
      let remainderArr = reversedArray.slice(indexToFind + 1)
      console.log(remainderArr)
      let sumRemainder = remainderArr.reduce((acc, el) => acc+el[1] , 0)
      if (sumRemainder < change && indexToFind < reversedArray.length - 1) {
        console.log(`Sum of remaining cash: ${sumRemainder}, Change needed: ${change}`);
        changeDue.innerText = `Status: INSUFFICIENT_FUNDS`
        break
      } else if (indexToFind === reversedArray.length-1) {
        if (reversedArray[indexToFind][1] < change) {
          console.log(`Sum of remaining cash: ${sumRemainder}, Change needed: ${change}`);
          changeDue.innerText = `Status: INSUFFICIENT_FUNDS`
          break
        }
      }
      console.log(`${findName(changeToGive)} (${changeToGive}) given ${(timesToGiveChange * changeToGive).toFixed(2)} times`)
      changeDue.innerHTML += `${findName(changeToGive)}: \$${(timesToGiveChange * changeToGive).toFixed(2)}</br>`
      change -= (changeToGive * timesToGiveChange).toFixed(2)
      updateUI(findName(changeToGive), (timesToGiveChange * changeToGive).toFixed(2))
      currencyUnitsAndNotes[changeToGive] -= timesToGiveChange
    }
  }
  console.log(currencyUnitsAndNotes)
}

const calcChange = (costPrice, cashGiven, drawerTotal) => {
  let change = cashGiven - costPrice
  if (change < 0) {
    alert("Customer does not have enough money to purchase the item")
  } else if (change === 0) {
    changeDue.innerText = "No change due - customer paid with exact cash"
  } else {
    //let cashInRegister = sumDrawer()
    //console.log(`Total_Change_in_Drawer: ${sumDrawer().toFixed(2)}`)
    
    if (drawerTotal < change) {
      changeDue.innerText = "Status: INSUFFICIENT_FUNDS"
      console.log(`INSUFFICIENT_FUNDS-${Date.now()}`)
    } else if (drawerTotal === change) {
      changeDue.innerText = "Status: CLOSED</br>"
      calcUnits(change)
      console.log(`CLOSED-${Date.now()}`)
    } else {
      changeDue.innerHTML = "Status: OPEN</br>"
      calcUnits(change)
    }
  }
}

purchaseBtn.addEventListener("click", () => {
  changeDue.innerHTML = ""
  calcChange(price, cashInput.value, sumDrawer())
  cashInput.value = ""
  console.log(`Total_Change_in_Drawer: ${sumDrawer().toFixed(2)}`)
})

cashInput.addEventListener("keydown", (key) => {
  if (key.key === "Enter") {
    changeDue.innerHTML = ""
    calcChange(price, cashInput.value, sumDrawer)
    cashInput.value = ""
    console.log(`Total_Change_in_Drawer: ${sumDrawer().toFixed(2)}`)
  }
})

Any help would be greatly appreciated!

Can you describe how we should recreate this? (What should we type?)

Just explain or drop a hint on why the status of Cash Register doesn’t update relative to the drawer sum.
Thank you.

to drop a hint or explain we need to see what’s wrong. Please describe how we can see this wrong behavior in your app