Tell us what’s happening:
I don’t know why the every value of cid
becomes 0
after the i
becomes zero. Is it that when I execute arr[i]
with i being negative then every array
Your code so far
const currArr=[0.01,0.05,0.1,0.25,1,5,10,20,100]
function checkCashRegister(price, cash, cid) {
let drawer=[...cid];
let change=(cash-price).toFixed(2);
const display=[];
// Here is your change, ma'am.
let i=8
while(change!=0 &&change>0){
//the loop below returns the highest currency in ehich we can give change
while((change/currArr[i])<1){
i--;
}
let changeToBePaid=Math.floor(change/currArr[i])*currArr[i]
if(changeToBePaid>drawer[i][1])changeToBePaid=drawer[i][1];
display.push([drawer[i][0],changeToBePaid])
change-=changeToBePaid;
drawer[i][1]-=changeToBePaid
change=change.toFixed(2);
i--;
if(i<0 &&change>0){
return {status: "INSUFFICIENT_FUNDS", change: []};
}
}
if(totalCashInDrawer(drawer)==0){return {status:"CLOSED",change:cid}}
return {status:"OPEN",change:display};
}
//counts cash in drawer after giving the change
function totalCashInDrawer(drawer){
let result=0;
for(let i=0;i<drawer.length;i++)result+=drawer[i][1];
return result;
}
// Example cash-in-drawer array:
// [["PENNY", 1.01],
// ["NICKEL", 2.05],
// ["DIME", 3.1],
// ["QUARTER", 4.25],
// ["ONE", 90],
// ["FIVE", 55],
// ["TEN", 20],
// ["TWENTY", 60],
// ["ONE HUNDRED", 100]]
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]]))
//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/79.0.3945.88 Safari/537.36
.
Challenge: Cash Register
Link to the challenge: