Hello, I’ve been picking away at the Cash Register challenge for a few weeks, now, and I’m royally stuck. I’ve had a pair-programming session that allowed me to logically get to where I am now, but I’m having a difficult time composing the algorithm that I need to loop through the existing Cash In Drawer (cid) array to subtract the correct amount of cash to create a new array that I can return.
So far, I’ve factored out the “easy” scenarios:
- amt in drawer is less than the change that is needed
- amt in drawer is equal to the change that is needed
I wasn’t sure how to subtract the correct denominational increments from the existing cid array, so I created an array of objects to store each denomination and what it’s worth. However, I’m stuck on how to marry these two together into a for
loop or some sort of reduce
or map
function.
function checkCashRegister(price, cash, cid) {
// initialize change variable to store the current change
var change = cash - price;
// initialize function response with an empty object
var response = { status: "", change: [] }
// initialize cidAmt to store the total amout of cash
// currently in the drawer
var cidAmt = cid.reduce( function (accumulator, current) {
return accumulator + current[1];
}, 0);
// handle easy scenarios first
// amt in drawer is less than the change that is needed
if ( cidAmt < change ) {
response.status = "INSUFFICIENT_FUNDS";
return response;
}
// amt in drawer is equal to the change that is needed
if ( cidAmt === change ) {
response.status = "CLOSED";
response.change = cid;
return response;
}
// need an array that contains the various denominations and their values
var denomValue = [
{bill: "ONE HUNDRED", val: 100},
{bill: "TWENTY", val: 20},
{bill: "TEN", val: 10},
{bill: "FIVE", val: 5},
{bill: "ONE", val: 1},
{bill: "QUARTER", val: 0.25},
{bill: "DIME", val: 0.10},
{bill: "NICKEL", val: 0.05},
{bill: "PENNY", val: 0.01}
];
// need to reverse the cid array to loop in reverse order
var cidDesc = cid.reverse(); // order the cid array from largest to smallest
for ( i = 0; i <= denomValue.length; i += 1 ) {
if ( cidDesc[i][1] > change ) {
change -= denomValue[i].val
} else {
return "else block";
}
}
// test area
// end test area
// Here is your change, ma'am.
return change;
}
// Example cash-in-drawer array:
// [["PENNY", 1.01],
// ["NICKEL", 2.05],
// ["DIME", 3.1],
// ["QUARTER", 4.25],
// ["ONE", 90],
// ["FIVE", 55],
// ["TEN", 20],
// ["TWENTY", 60],
// ["ONE HUNDRED", 100]]
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]]);