Tell us what’s happening:
Hello Fellow Campers,
I am trying to be smart here and use a recursive function. However, as it turns out, I’m not smart enough to actually write the correct code. From my console logs it seems that the recursive function only really uses the coins it calculates on the last function call that is being resolved.
The idea here is that it checks if the change is larger than the largest bill / coin there is in the drawer. If so, it takes that bill / coin returns it to the customer, decreases the change due and the money in the drawer. The functions calls itself until there is no more change left to return and exits returning the coins / bills that need be handed to the customer.
Any pointers as to why is only returns the most recent function call? Thanks in advance guys.
Your code so far
function checkCashRegister(price, cash, cid) {
var change = cash - price;
var totalMoney = 0;
const IF = "INSUFFICIENT_FUNDS";
var message = {
status: "Default",
change : []
};
// array mapping for European dummies
cid[0][0] = 0.01;
cid[1][0] = 0.05;
cid[2][0] = 0.1;
cid[3][0] = 0.25;
cid[4][0] = 1;
cid[5][0] = 5;
cid[6][0] = 10;
cid[7][0] = 20;
cid[8][0] = 100;
console.log(cid);
// checking for no cash
for (var coin in cid) {
totalMoney += cid[coin][1];
console.log(totalMoney);
}
if (change > totalMoney) {
message.status = IF;
message.change = [];
return message;
}
// invoking recursive change function
console.log(calcChang(change, cid));
message.change = calcChang(change, cid);
console.log(message);
return message;
}
function calcChang(change, cid, coins){
var coins = [
["PENNY", 0],
["NICKEL", 0],
["DIME", 0],
["QUARTER", 0],
["ONE", 0],
["FIVE", 0],
["TEN", 0],
["TWENTY", 0],
["ONE HUNDRED", 0]
];
for (var i = 8; i >= 0; i--){
if (change >= cid[i][0]){
console.log("Here's some change");
coins[i][1] += cid[i][0]; // add to the coins given to customer
change -= cid[i][0]; // decrease the change due by the value of the coin
cid[i][1] -= cid[i][0]; // decrease cash in drawer
calcChang(change, cid, coins);
}
}
return coins;
}
// 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]]);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.79 Safari/537.36
.
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/cash-register