JavaScript Algorithms and Data Structures Projects - Cash Register

Hi! So I´m havings some troubles with the change array, instead of returning change: [ [ 'QUARTER', 0.25 ], [ 'QUARTER', 0.25 ] ], I need it to return change: [ [ 'QUARTER', 0.5 ] ], but Im not being able to figure how to do it.
Thanks in advance!

Your code so far

function checkCashRegister(price, cash, cid) {
  let cashInDrawer = cid;
  let cashInDrawerReverse = cashInDrawer.reverse()
  let currencyUnits = [
     ["ONE HUNDRED", 100],
     ["TWENTY", 20],
     ["TEN", 10],
     ["FIVE", 5],
     ["ONE", 1],
     ["QUARTER", 0.25],
     ["DIME", 0.1],
     ["NICKEL", 0.05],
     ["PENNY", 0.01]
  ];

  let availableMoney = [];
  let totalAvailableMoney = 0;
  let totalChange = cash - price;
  let change = []
  
  //Check the available money:
  for(let index = 0; index < cid.length; index++){
    availableMoney.push(cid[index][1]);
  }
  availableMoney.reverse();

  //Total of available money:
  
  for(let f = 0; f < availableMoney.length; f++){
    totalAvailableMoney += availableMoney[f];
  }

  //Returns:

  if(totalChange > totalAvailableMoney){
    return {status: "INSUFFICIENT_FUNDS", change: []}
  }

  else if (totalChange === totalAvailableMoney){
    return {status: "OPEN", change: cashInDrawer}
  }

   else {
    for(var i = 0; i < cashInDrawerReverse.length; i++){
     if(cashInDrawerReverse[i][1] != 0){
      while(totalChange >= currencyUnits[i][1]){
        /*Check if that currency unit is already present in the 
change array, here is where i´m having some troubles*/
        if(change.indexOf(currencyUnits[i][0]) >= 0){
          let indexOf = change.indexOf(currencyUnits[i][0]);
          change[indexOf][1] += currencyUnits[i][1]
        } else{
          change.push(currencyUnits[i]);
        }
          cashInDrawer[i][1] -= currencyUnits[i][1];
          totalChange -=  currencyUnits[i][1]
        }
      }
    }
    
    return {status: "OPEN", change: change}
  }


}

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

Your browser information:

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

Challenge: JavaScript Algorithms and Data Structures Projects - Cash Register

Link to the challenge:

currentyUnits[i][0] is a string but it appears that you want to use change as a multi-dimensional array. So using indexOf to find the first occurrence of a string in a multi-dimensional array isn’t going to work. The indexOf method won’t dive down into each subarray in change.

1 Like

Ohh, true! Thank you!
So i should do an iteration in order to find the index, right?

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