JS Cash Register Output Help

Hi, my outputs match all of the test cases’ expected outputs but it is still marked wrong? Am I not seeing something?

var currency = [["PENNY","NICKEL","DIME","QUARTER","DOLLAR","FIVE","TEN","TWENTY","ONE HUNDRED"],[0.01,0.05,0.10,0.25,1,5,10,20,100],[]];

function checkCashRegister(price, cash, cid) {
  var changeDue = Math.round((cash - price) * 100) /100;
  var changeString = [
  ["PENNY", 0],
  ["NICKEL", 0],
  ["DIME", 0],
  ["QUARTER", 0],
  ["ONE", 0],
  ["FIVE", 0],
  ["TEN", 0],
  ["TWENTY", 0],
  ["ONE HUNDRED", 0]];
  var cashDrawer = cid;
  for (let i = 0; i < cashDrawer.length; i++) {
    currency[2].push(Math.round(cashDrawer[i][1] / currency[1][i]));
  }
  
  for (let i = currency[1].length - 1; i >= 0; i--) {

    while (currency[1][i] <= changeDue && currency[2][i] > 0) {
      changeString[i][1] = Math.round((changeString[i][1] + currency[1][i]) * 100) / 100;
      currency[2][i]--;
      changeDue = Math.round((changeDue - currency[1][i])*100) / 100;

    }

  }


  if (changeDue == 0) {

    if (checkEmpty(currency[2])) {
      return {status:"CLOSED", change:changeString};
    } else {
      changeString = changeString.filter(x => x[1] > 0);
      return {status: "OPEN", change: changeString.reverse()};
    }

  } else {
    return {status: "INSUFFICIENT_FUNDS", change: []};
  }

}

function checkEmpty(arr) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] != 0) {
      return false;
    }
  }
  return true;
}

console.log(checkCashRegister(3.26, 100, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]]));

Hello and welcome to the FCC community~!

I tried removing this line, and that got your code to pass on my end. What that tells me, though, is that your code does not “clean up” after itself. In other words, there’s a variable somewhere that’s not being cleared properly and causes the function to return a different result.
So I took a look:


It looks like it keeps the value of the change due after each function call? I’m really not quite sure what is causing this.

1 Like

Thanks a lot! Yeah you were right, I just realized it’s because I stored the count outside the function and it never got cleared between functions calls.

1 Like

I am glad you were able to find the bug! console.log() is your friend. :slight_smile: