Hi there,
I’m working on the last challenge of the JavaScript Algorithms and Data Structures Course, which is to build a Cash Register. Obviously, I am not finished yet, but I am stuck on one problem (before continuing) - to understand it I’ll show you my code, first.
function checkCashRegister(price, cash, cid) {
let change = cash - price;
console.log("change: " + change);
const currencyVal = {
"ONE HUNDRED": 100,
"TWENTY": 20,
"TEN": 10,
"FIVE": 5,
"ONE": 1,
"QUARTER": 0.25,
"DIME": 0.1,
"NICKEL": 0.05,
"PENNY": 0.01
}
const cidSum = cid.reduce((acc, val) => {
if(!isNaN(acc + val[1])) {
return acc + val[1];
}
}, 0);
const revCid = cid.reverse();
let changeObj = {}
function calculateChange() {
for(let unit in currencyVal) { // loop through each Currency Unit
revCid.forEach(amount => { // loop through each amount
if(amount[1] >= currencyVal[unit] && amount[0] === unit) { // check what I have in cash-in-drawer
while(change - currencyVal[unit] >= 0 && amount[1]) {
// calculate the change and convert it into an object
console.log(unit, currencyVal[unit]);
if(Object.keys(changeObj).length === 0 && changeObj.constructor === Object) {
changeObj[unit] = currencyVal[unit];
} else {
if(changeObj.hasOwnProperty(unit)) {
changeObj[unit] += currencyVal[unit];
}
if(!changeObj.hasOwnProperty(unit)) {
changeObj[unit] = currencyVal[unit];
}
}
change -= currencyVal[unit];
amount[1] -= currencyVal[unit];
}
}
});
}
let changeArr = Object.entries(changeObj); // convert changeObj into an Array
return changeArr;
}
if(change < 0 || change > cidSum) {
return {status: "INSUFFICIENT_FUNDS", change: []}
} else {
return {status: "OPEN", change: calculateChange()};
}
}
console.log(checkCashRegister(3.26, 100, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]]));
So, if you run this code, you’ll notice that there’s just 0.01 PENNY missing. I want to pay my imaginary customers fully, so I need help Where’s the issue? This is the first time, I’m asking on this forum, please forgive me, if I missed something on this post. I appreciate any solution!