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