Hello everyone. I just finished the javascript Cash Register project and I’m happy with the way it turned out. I would like to share my solution with you guys since it seems like it could be valuable. I recently learned about the Map object and discovered that it could be really useful in solving this project.
Let me know what you guys think of it and please let me know of any improvements that I could make:
function checkCashRegister(price, cash, cid) {
var change = Math.round((cash - price)*100);
var changeArr = [];
var moneyVal = {
"ONE HUNDRED": 10000,
"TWENTY": 2000,
"TEN": 1000,
"FIVE": 500,
"ONE": 100,
"QUARTER": 25,
"DIME": 10,
"ONE": 100,
"NICKEL": 5,
"PENNY": 1
};
var changeDrawer = new Map(cid.reverse());
//multiply everything by 100
for (var [key, value] of changeDrawer){
changeDrawer.set(key, Math.round(value*100));
}
for (var [key, value] of changeDrawer){
var tempChangeArr = [];
while (change >= moneyVal[key] && changeDrawer.get(key) >= moneyVal[key]){
change -= moneyVal[key];
changeDrawer.set(key, changeDrawer.get(key) - moneyVal[key]);
//Add to "status:OPEN" array.
tempChangeArr[0] = key;
if (tempChangeArr[1] === undefined) tempChangeArr[1] = 0;
tempChangeArr[1] += moneyVal[key];
}
if (tempChangeArr[1] !== undefined){
tempChangeArr[1] = tempChangeArr[1] / 100;
}
if (tempChangeArr.length > 0){
changeArr.push(tempChangeArr);
}
}
var sumOfCID = cid.reduce(function(acc, cur){
return acc + cur[1];
},0);
if (change > 0){
return {status: "INSUFFICIENT_FUNDS", change: []};
} else if ((cash - price) === sumOfCID){
return {status: "CLOSED", change: cid.reverse()};
} else {
return {status: "OPEN", change: changeArr};
}
return change;
}