So I am trying to save initial copy of cid into variable initialCid. I found one method Array.from() that does a deepcopy. Why isn’t this working when I assign initialCid to cid? initialCid also changes by the time Program reaches at result = initialCid; Please someone help.
function checkCashRegister(price, cash, cid) {
let change = cash - price;
let totalCid = 0;
const initialCid = Array.from(cid);//save deep copy!!!!!!!!!!HELP!!!!!!!!!!!!!!!!!
let currencyUnit = [["PENNY", 0.01], ["NICKEL", 0.5], ["DIME", 0.1], ["QUARTER", 0.25], ["ONE", 1.0], ["FIVE", 5.0], ["TEN", 10.0], ["TWENTY", 20.0], ["ONE HUNDRED", 100.0]];
let count = 0;
let result = [];
let status = "";
let initialChange = change;
for(let i = 0;i < cid.length;i++){
totalCid += cid[i][1];
}
if (change > totalCid) {
return {status: "INSUFFICIENT_FUNDS", change: []};
}
//console.log(change);
//find how many times we can subtract
for(let i = 0;i < cid.length;i++){
cid[i][2] = cid[i][1] / currencyUnit[i][1];
}
for(let i = currencyUnit.length-1;(i >= 0);i--){
if(change >= currencyUnit[i][1]){
//if 3rd array value
while((count < cid[i][2])&&(change >= 0)&&(change >=currencyUnit[i][1])){
change = Math.round(change*100)/100;
cid[i][1] = Math.round(cid[i][1]*100)/100;
//console.log("change = ",change,", i = ",i,", count = ",count,", cid[i][2] = ",cid[i][2],", cid[i][1] = ",cid[i][1]);
change -= currencyUnit[i][1];
cid[i][1] -= currencyUnit[i][1];
count++;
}
//console.log(change, cid[i][1],i);
result.push([cid[i][0],currencyUnit[i][1]*count]);
//check in cid how many times we can subtract;
}
count = 0;
}
if(change != 0){
return {status: "INSUFFICIENT_FUNDS", change: []};
}
//console.log(change + " total " + totalCid);
if (change !== 0){
status = "INSUFFICIENT_FUNDS";
result = [];
} else if ((change === 0)&&(initialChange === totalCid)){
status = "CLOSED";
result = initialCid;//!!!!!!!!!!!!HELP!!!!!!!!!!!!!!!!
}
else{
status = "OPEN";
}
return {status: status, change: result};
}
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]]));