Hi guys, I have been working on the cash register for the last couple of days, and I THINK I am getting closer to the solution. So far I have completed all the other projects without looking at solutions, and I REALLY don’t want to look at how to solve this one and I want to do it myself, but I think I am stuck and need a little help to get there. So far this is my code:
function checkCashRegister(price, cash, cid) {
const valueTable = {
"ONE HUNDRED": 100,
"TWENTY": 20,
"TEN": 10,
"FIVE": 5,
"ONE": 1,
"QUARTER": 0.25,
"DIME": 0.1,
"NICKEL": 0.05,
"PENNY": 0.01
}
var change = [];
var changeDue = cash - price;
// figure out total cid
var totalDrawer = 0;
for (let i = 0; i < cid.length; i++) {
totalDrawer+= cid[i][1];
}
// if change > total cid
if (changeDue > totalDrawer) {
return {status: "INSUFFICIENT_FUNDS", change: []}
}
// loop through drawer to give change
for (let i = cid.length - 1; i >= 0; i--) {
if(changeDue >= valueTable[cid[i][0]]) {
var temp = [];
var changeGiven = 0;
temp.push(cid[i][0])
while(changeDue - valueTable[cid[i][0]] >= 0 && cid[i][1] !== 0) {
cid[i][1] -= valueTable[cid[i][0]];
changeDue -= valueTable[cid[i][0]];
changeGiven += valueTable[cid[i][0]];
}
temp.push(changeGiven);
change.push(temp)
}
}
// return status OPEN and change given if change has been given successfully
if (changeDue == 0) {
return {status: "OPEN", change: change}}
// if change wasn't given successfully return insufficient funds
else return {status: "INSUFFICIENT_FUNDS", change: []}
}
I know this isn’t complete yet. I still haven’t handled the case where change is given successfully and is exactly the available change in the drawer, giving status: CLOSED as output.
But this passes a few tests already, and I noticed it fails a test that it SHOULD pass:
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]])
And the reason it fails this test is because change gets lost in the way when Javascript handles decimal numbers, and the changeDue variable never gets to 0 but there is always a very small number left. (I know this by doing a few console.log in strategic places).
Now my question is, before I keep working on this approach. Is it fixable? if it is, where do I look for solutions to this problem? Any help or hint that will help me move forward is highly appreciated!!
thank you!