The exercise is: Cash Register
Here my solution, please give me your feedback
function moneyValueToName(value){
switch(value){
case 0.01: return "PENNY";
case 0.05: return "NICKEL";
case 0.10: return "DIME";
case 0.25: return "QUARTER";
case 1: return "ONE";
case 5: return "FIVE";
case 10: return "TEN";
case 20: return "TWENTY";
case 100: return "ONE HUNDRED";
default: return undefined;
}
}
function checkCashRegister(price, cash, cid) {
let change = {};
let drawer = Object.fromEntries(cid) //crete Object from cid
let totalReturnChange = cash-price;
/* Array used to find minimun cash value */
let money = [100, 20, 10, 5, 1, 0.25, 0.10, 0.05, 0.01];
var retObj = {};
while(totalReturnChange > 0 ){
let minMoney = money.find(element => element <= totalReturnChange); //find minimun cash value
if(minMoney === undefined){
break; //exit from while because there isn't a minimun cash value
}
let moneyName = moneyValueToName(minMoney);
if(drawer.hasOwnProperty(moneyName) && drawer[moneyName] > 0){
drawer[moneyName] = (drawer[moneyName]).toFixed(2) - minMoney;
totalReturnChange = (totalReturnChange - minMoney).toFixed(2);
if(drawer[moneyName] === 0)
money.splice(money.indexOf(minMoney), 1); //remove from money the element that have value 0 in drawer
if(change.hasOwnProperty(moneyName))
change[moneyName] = parseFloat((Number(change[moneyName]) + minMoney).toFixed(2)); //convert in float the value width 2 decimal
else
change[moneyName] = minMoney;
}
else {
if(drawer[moneyName] === 0)
money.splice(money.indexOf(minMoney), 1);
}
}
const changeValues = Object.values(change);
let totalValues = 0;
changeValues.forEach(el => totalValues += el);
if (totalValues < totalReturnChange)
retObj = {status: "INSUFFICIENT_FUNDS", change: []};
else{
let allZeroValues = Object.values(drawer).every(el => el === 0);
if(allZeroValues){
retObj.status = "CLOSED";
for (const property in change) {
drawer[property] = change[property];
}
retObj.change = Object.entries(drawer);
}
else{
retObj.status = "OPEN";
retObj.change = Object.entries(change);
}
}
return retObj;
}
Thanks and good code at all.
Luca