How to get the original cid- Cash Register

Continuing the discussion from freeCodeCamp Challenge Guide: Cash Register:
I took a very long time in coming up with this. There is this problem of copying the cid, without copying the reference. I couldn’t figure it out till the end so found a work around. But will really appreciate if some one can tell.
All the ways, including […cid] seem to copy by reference only.

function checkCashRegister(price, cash, cid) {
 var change = ((cash - price)*100);
 var currency = [1, 5, 10, 25, 100, 500, 1000, 2000, 10000];
 var sum = 0;
var value = [];
 var mapCid = cid.map(x => Math.round(x[1]*100)); 
 var sumOfCid = function(cid){
  
   for(var i = 0; i < mapCid.length; i++){
     if(change >= currency[i]) {
       sum += mapCid[i]
     }    
   }; return sum;
 }; 
var leftCurr = sumOfCid(cid) ;
 if(change === leftCurr) {
   return{status: "CLOSED", change: cid};
 } else if (change > leftCurr) {
   return{status: "INSUFFICIENT_FUNDS", change: []};
 } else {
   let ans = [];
 

    for(var i = mapCid.length - 1; i>=0 ; i--){
      
      let temp = 0;
        while(change >= currency[i] && mapCid[i]>=currency[i]){
          change -= currency[i];
          mapCid[i] -= currency[i];
          temp += currency[i];
        }
          if(temp!=0)ans.push([cid[i][0],temp/100]);
       // console.log(ans);
    }
   
    return {status :"OPEN", change : ans};
 }
}

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]]);
1 Like

You can’t use shallow copying for nested arrays/objects.

JS now has the structuredClone function you can use when available. If it isn’t and without having to create your own deep copy function JSON.stringify() and JSON.parse() is also an option.


const 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 shallowClone = [...cid];
shallowClone[0][1] = 1.03;
console.log(cid[0][1] === shallowClone[0][1]); // true

const deepClone = structuredClone(cid);
deepClone[0][1] = 1.04;
console.log(cid[0][1] === deepClone[0][1]); // false

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