Throughout the JS algorithm scripting challenges, I got in the habit of first solving a problem on my own, then checking and improving my work by studying the provided answers and comments of others. However, since answers and comments are now turned off for JS projects, I’d really appreciate some feedback on my code for the final JS project: Cash Register.
Here’s how I solved this challenge…
function checkCashRegister(price, cash, cid) {
// define basic variables
const referenceTable = {
"PENNY": 0.01, "NICKEL": 0.05, "DIME": 0.1, "QUARTER": 0.25, "ONE": 1, "FIVE": 5, "TEN": 10, "TWENTY": 20, "ONE HUNDRED": 100
}
let changeDue = cash-price
let totalCID = 0;
for (let i=0; i<cid.length; i++) {
totalCID += cid[i][1]
};
// calculate change to be given, if available
let changeGiven = []
for (let i=8; i>=0; i--) {
let currentValue = referenceTable[cid[i][0]]
let currentAvailable = cid[i][1]
let currentChangeGiven = 0
while (changeDue >= currentValue && currentAvailable > 0) {
changeDue = (changeDue - currentValue).toFixed(2)
currentAvailable -= currentValue
totalCID = (totalCID - currentValue).toFixed(2)
currentChangeGiven += currentValue
}
if (currentChangeGiven > 0) {
changeGiven.push([cid[i][0], currentChangeGiven]);
}
}
// determine output based on result of calculations
if (changeDue > 0) {
return {status: "INSUFFICIENT_FUNDS", change: []}
} else if (totalCID == 0) {
return {status: "CLOSED", change: cid}
}
return {status: "OPEN", change: changeGiven};
}
Please let me know if you spot any mistakes, know of any ways to simplify my code, or even if this approach is totally improper/ would take too long to run.
Thanks so much for your feedback!!