I am trying to create a copy of original array that i have received as an argument passed to the function. I am performing operations on the copied array but still my main array is getting mutated.I don't want to change the value of cid that i received originally. I have tried a plenty of ways like copying through slice(),concat() and spread operator but still my main (cid)array is getting mutated. Help me to get rid of this. Thanks in advance..
let copierFunction=(...a)=>{
let b= [...a]
return(b)
}
let originalCID = cid.filter((e)=>{
if(e){
return e
}
})
let cashInDrawer=copierFunction(...cid);
let toBeReturned = cash-price;
let currencyRefrence= [['PENNY',0.01],['NICKEL',0.05],['DIME',0.1],['QUARTER',0.25],['ONE',1],['FIVE',5],['TEN',10],['TWENTY',20],['ONE HUNDRED',100]];
currencyRefrence = currencyRefrence.reverse()
let change=[]
function returnChange(a){
if(a==0){
return null;
}
for(let i=0;i<currencyRefrence.length;i++){
let returnUnit = a / currencyRefrence[i][1]
if(returnUnit>=1){
let chutte = parseInt(returnUnit)*currencyRefrence[i][1];
for(let j=0;j<cashInDrawer.length;j++){
if(cashInDrawer[j][0] == currencyRefrence[i][0]){
if(cashInDrawer[j][1]>=currencyRefrence[i][1]){
if(cashInDrawer[j][1]>chutte){
change.push([cashInDrawer[j][0],chutte])
a= a-chutte;
a= a.toFixed(2)
cashInDrawer[j][1]= cashInDrawer[j][1]-chutte
return returnChange(a);
}else{
change.push([cashInDrawer[j][0],cashInDrawer[j][1]])
a= a-cashInDrawer[j][1];
a= a.toFixed(2)
cashInDrawer[j][1]= 0;
return returnChange(a);
}
}
}
}
}
}
}
returnChange(toBeReturned);
function statusChecker(cashInDrawer,change){
//checking if change is given or not.
let returnedAmount=(change.reduce((a,e)=>{
return( a + e[1])
},0)).toFixed(2)
if(toBeReturned > returnedAmount ){
return 'INSUFFICIENT_FUNDS'
}
//checking if cashInDrawer is empty after change.
let amountIncashInDrawer = (cashInDrawer.reduce((a,e)=>{
return( a + e[1])
},0)).toFixed(2)
if(amountIncashInDrawer==0){
return 'CLOSED'
}
return 'OPEN';
}
let status = statusChecker(cashInDrawer,change)
if(status =='INSUFFICIENT_FUNDS'){
return {status:status,change:[]}
}
if(status == 'CLOSED'){
return {status:status,change: 'originalCID'}
}
return {status:'OPEN',change:change}
}
console.log(checkCashRegister(19.5, 20, [["PENNY", 0.5], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]])); ```