# [Javascript] Cash register project

Hi there,

I would like to have some feedback on my solution for the cash register project. Here is the link to the project :

And here is my code :

``````function checkCashRegister(price, cash, cid) {
//initialization of the status and the change array
var status="";
var change=[
["PENNY", 0],
["NICKEL", 0],
["DIME", 0],
["QUARTER", 0],
["ONE", 0],
["FIVE", 0],
["TEN", 0],
["TWENTY", 0],
["ONE HUNDRED", 0]
];
//computation of the due change and total cash in CID
var changeDue = toPrecise(cash-price);
var totalCash=toPrecise(cid.map(element => element).reduce((a,b) =>a+b));
//Exit case : if there isn't enough money in CID
if(toPrecise(changeDue-totalCash)>0){
return {status:"INSUFFICIENT_FUNDS", change:[]};

} else{
//for each type of money...
for(let i=cid.length-1;i>=0; i--){
//while there is still money in the cid, change to give, and change - current money is positive
while(cid[i]>0
&&changeDue>0
&&toPrecise(changeDue-currencyToAmount(cid[i]))>=0){
change[i]=change[i]+currencyToAmount(cid[i]);
cid[i]=toPrecise(cid[i]-currencyToAmount(cid[i]));
changeDue=toPrecise(changeDue-currencyToAmount(cid[i]));
}
}
}
//re computation of the total cash in CID
totalCash=cid.map(element => element).reduce((a,b) =>a+b);
//If there is still change due after :
if(changeDue>0&&totalCash!=0){
return {status:"INSUFFICIENT_FUNDS", change:[]};
//If all the cash is given :
} else if(toPrecise(changeDue-totalCash)==0){
return {status:"CLOSED",change:change
.map(element => [element, parseFloat(toPrecise(element))])};
//If there is still cash in the cid after giving the change :
} else{
return {status:"OPEN", change:change.filter(element => element!=0).reverse()};
}
}

function toPrecise(expression){
return expression.toFixed(2);
}

function currencyToAmount(name){
switch(name){
case "PENNY":
return 0.01;
break;
case "NICKEL":
return 0.05;
break;
case "DIME":
return 0.1;
break;
case "QUARTER":
return 0.25;
break;
case "ONE":
return 1;
break;
case "FIVE":
return 5;
break;
case "TEN":
return 10;
break;
case "TWENTY":
return 20;
break;
case "ONE HUNDRED":
return 100;
break;
}
}

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

If you prefer, I put in in a codepen.io to play and test it :
https://codepen.io/tpeyron/pen/PomPbVw?editors=0010

I really struggled with the float representation. I’ve followed the advices given in this topic :

But I found that the `currencify` function can’t be used everywhere, and `.toFixed(2)` as well.

I would very much appreciate to have some feedback about where to use or not
`.toFixed(2)` !

Cheers,

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.