Cash Register - help

Tell us what’s happening:
For some reason, the array “cid” is also being modified when I call the map method on it to assign the returned array to “resultingArray.” The “cid” array also has it’s values turned into 0. Can someone please explain why?

Edit: oh wait I think I know why. It’s because the reference to “cid” is getting passed into the anonymous function. I thought it was a copy of cid… BUT I wanna know why “origArr” also has its values turned into 0. It’s declared and defined before the map method is called.

Your code so far



function checkCashRegister(price, cash, cid) {
  let change = cash - price;
  let total = 0;
  for (let i = 0; i < cid.length; i++) {
    total += cid[i][1];
  }
  if (total < change) {
    return {status: "INSUFFICIENT_FUNDS", change: []};
  }
  if (total === change) {
    return {status: "CLOSED", change: [...cid]};
  }
 let origArr = [...cid];
  let resultArr = origArr.map(x => {
    x[1] = 0;
    return x;
  });
  let denom;
  for (let i = origArr.length - 1; i >= 0; i--) {
    switch (origArr[i][0]) {
      case "ONE HUNDRED":
        denom = 100;
        break;
      case "TWENTY":
        denom = 20;
        break;
      case "TEN":
        denom = 10;
        break;
      case "FIVE":
        denom = 5;
        break;
      case "DOLLAR":
        denom = 1;
        break;
      case "QUARTER":
        denom = .25;
        break;
      case "DIME":
        denom = .1;
        break;
      case "NICKEL":
        denom = .05;
        break;
      case "PENNY":
        denom = .01;
    }
    while (change - denom > 0 && origArr[i][1] > 0) {
      change -= denom;
      origArr[i][1] -= denom;
      resultArr[i][1] += denom;
    }
    if (change === 0) {
      return {status: "OPEN", change: resultArr.filter(x => x[1] !== 0)};
    }
    //console.log(resultArr);
  }
  return {status: "INSUFFICIENT_FUNDS", change: []};
}

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; rv:60.0) Gecko/20100101 Firefox/60.0.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/cash-register/

[…cid] makes a shallow copy of arr, that means that if cid is an array of arrays, the references to the inner arrays are copied and no their elements, but if cid were an array of numbers there would be no problem with a shallow copy.

Watch

2 Likes