I just finished the final project of JavaScript Algorithms and Data Structures and I’d like some feedback on my solution.
Please help me improve by letting me know I did wrong or could do better, thanks!
P.S. I’ve realized that multiplying my numbers by 100 doesn’t actually solve any precision errors so I’m aware of that. Also, I think the variable naming could use some work.
function checkCashRegister(price, cash, cid) {
const change = Math.round((cash - price) * 100);
const total = cid.reduce((bal, currBill) => bal + (currBill[1] * 100), 0);
// check if our CID value is exactly equal to our change
if (total === change) {
return {
status: "CLOSED",
change: cid
}
}
const bills = computeChangeInBills(change, cid);
if (bills.length) {
return {
status: "OPEN",
change: bills
}
}
return {
status: "INSUFFICIENT_FUNDS",
change: []
}
}
function computeChangeInBills(change, cashDrawer) {
const billLegend = {
"ONE HUNDRED": 10000,
"TWENTY": 2000,
"TEN": 1000,
"FIVE": 500,
"ONE": 100,
"QUARTER": 25,
"DIME": 10,
"NICKEL": 5,
"PENNY": 1
}
const changeBills = [];
// leftovers holds the amount of change that is leftover after all currency types are exhausted
const leftOvers = cashDrawer.reverse().reduce((changeLeft, bill) => {
const billInCents = Math.round(bill[1] * 100);
// if the value of the bill is greater than changeLeft, then skip the bill
if (billLegend[bill[0]] > changeLeft) {
return changeLeft;
}
// otherwise, if the total monetary value of all of 1 type of bill is less than changeLeft, push all available bills to change array
if (billInCents < changeLeft) {
changeBills.push(bill);
return changeLeft - billInCents; // decrease change left to compute
}
// final case is the bills can be used but there are more bills than needed, so we compute the maximum amount that won't exceed the change left
const maxPossibleBills = (billLegend[bill[0]] * Math.floor((changeLeft / billLegend[bill[0]])));
changeBills.push([bill[0], maxPossibleBills / 100]);
return changeLeft - maxPossibleBills; // decrease change left to compute
}, change);
if (leftOvers) { // if leftovers isn't 0 (meaning truthy) then it means we can't return exact change
return [];
}
return changeBills;
}
checkCashRegister(19.5, 20, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]]);