Hey everyone.
Congratulations on making it to the end of the Fall 2022 cohort of the free JavaScript Bootcamp. It’s always bittersweet to make it here, but I am proud of each and every one of you for making it this far.
With that said, let’s post our solutions!
Here’s mine:
const DENOMINATIONS = {
PENNY: 1,
NICKEL: 5,
DIME: 10,
QUARTER: 25,
ONE: 100,
FIVE: 500,
TEN: 1000,
TWENTY: 2000,
"ONE HUNDRED": 10000
}
function checkCashRegister(price, cash, cid) {
// calculate amount of change due
const changeDue = cash - price;
let changeDueCents = changeDue * 100;
const centsInCid = cid.reduce((acc, slot) => {
return acc + slot[1] * 100;
}, 0);
if (centsInCid === changeDueCents) {
return {status: "CLOSED", change: cid};
}
// cid like array
const changeInHand = cid.reverse().map(([name, valueInSlot]) => {
// Start accumulating amount of money we'll give worth of that money type
let total = 0;
// Look up the denomination
const denomination = DENOMINATIONS[name]
// Get the value in the slot in cents
let valueCents = valueInSlot * 100;
// Loop: while the change due is worth more than the denomination, and while we still have money of that type in the drawer
while(valueCents > 0 && denomination <= changeDueCents) {
// Add one worth of that denomination to the total
total += denomination;
// Subtract that amount from the change Due
changeDueCents -= denomination;
// Subtract that amount from the amount in the slot
valueCents -= denomination;
//console.log({name, total, changeDueCents, valueCents})
}
return [name, total / 100]
})
.filter(([, value]) => value > 0);
// If I still owe change, we don't have sufficient funds
if (changeDueCents > 0) {
return {status: "INSUFFICIENT_FUNDS", change: []}
}
return {status: "OPEN", change: changeInHand}
}
console.log(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]]));