Hello all After quite a while i finally finished Cash Register project (yeah!! thats happiness ^___^)! but the construction feels monstrous, guess i misunderstand smth approach-wise.
Any quick thoughts/tips about what i got wrong would be much appreciated
function checkCashRegister(price, cash, cid) {
function makePrecise(num){
return +num.toFixed(2);
}
function getCidTotal(arr){
return arr.reduce((all,item)=>{
all+=item[1];
return makePrecise(all);
},0);
}
//coins and bills values
let coins = [["PENNY", 0.01],
["NICKEL", 0.05],
["DIME", 0.1],
["QUARTER", 0.25],
["ONE", 1],
["FIVE", 5],
["TEN", 10],
["TWENTY", 20],
["ONE HUNDRED", 100]],
change=cash-price,
cidTotal = getCidTotal(cid);
if(cidTotal<change){//dont have cash 4 this
return {status: "INSUFFICIENT_FUNDS", change: []};
}else if(cidTotal===change){//give away everything we've got
return {status: "CLOSED", change: cid};
} else{
// Here is your change, ma'am.
let resArr=[]; //array for change
//action part
for(let i=cid.length-1; i>=0; i--){//going through arr or cid/coing length backwards
if(coins[i][1]<change){//find first coin which value which is less than change
var coinSumOfKind=0;
while(change>0&&cid[i][1]>0&&(change-coins[i][1])>=0){
//while we still have change to give
//and have cid
//and next while iter doesnt make change negative
change= makePrecise(change);
change-= coins[i][1]; // remove coin from change
cid[i][1]-=coins[i][1];// remove coin from cid
coinSumOfKind+=coins[i][1];// keep track of current coin total val
} resArr.push([coins[i][0],coinSumOfKind]); //push resulting item [coinName,sumofkind] to arr
}
}
if(change>0){return {status:"INSUFFICIENT_FUNDS", change: []};}
return {status:"OPEN", change: resArr};
}
}