Tell us what’s happening:
Hey fellas! i am in the last challenge to end the data structures and algorithms section , but i got a weird problem
my solution for the cash register project consists of making a clone for the Cid array called “original” , and i enter a for loop that will iterate through the cid array and mutate it if it necessarily.
then when i quit the loop i will compare between the “cid” and the original cid array called “original”
the problem is that “original” is mutated too and it became a clone of cid so i cant compare and get the change.
i dont understand why i got this problem
and thanks for help!
Your code so far
var currency = {
"Penny" : 0.01,
"NICKEL" : 0.05,
"DIME" : 0.1,
"Quarter":0.25,
"ONE":1,
"FIVE": 5,
"TEN": 10,
"TWENTY": 20,
"ONE HUNDREAD":100
}
function checkCashRegister(price, cash, cid) {
var change =0;
var rest = cash - price;
var original = cid.slice(0);
console.log("cid clone before the loops");
console.log(original);
for(var i= cid.length-1;i>=0 && change<rest;i--){
while(cid[i][1]!=0 && change<rest && change+currency[cid[i][0]]<= rest ){
change+=currency[cid[i][0]];
cid[i][1]= cid[i][1]- currency[cid[i][0]];
}
}
console.log("cid clone after the loops ");
console.log(original);
console.log(change);
change = original.filter((v,i)=>v[1]!=original[i][1]);
console.log("change");
console.log(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) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36 Edg/84.0.522.40
.
Challenge: Cash Register
Link to the challenge: