WARNING: RUNNING THIS CODE WILL CRASH YOUR BROWSER
For some reason, when I run the recursive function I have below in my function, my browser crashes and which is most likely due to infinite loop or the max call stack size being exceeded. This is my code for Exact Change. However, I am not looking for the solution to the algorithm, but only the solution to fixing my code or more precisely my function.
I’m utilizing the recursive function in my code because I am trying to take the total change and subtract the selected currency value from the total change until either it can no longer be subtracted from the total because it will result in a negative number or zero or there is no longer anymore of that form of payment(which is given as an argument). In the code, I test this is only one array item not all of them simultaneously.
function checkCashRegister(price, cash, cid) {
var currencyValues = {
"PENNY": 0.01,
"NICKEL": 0.05,
"DIME": 0.1,
"QUARTER": 0.25,
"ONE": 1,
"FIVE": 5,
"TEN": 10,
"TWENTY": 20,
"ONE HUNDRED":100
};
//----------FIXED AND WORKS NOW------------------------
var singleArr = [];
var reverseCID = cid.reverse();
for (var i = 0; i < reverseCID.length; i++) {
if (currencyValues[reverseCID[i][0]] <= cash - price) {
singleArr.push(reverseCID[i]);
}
}//for loop
//-------------------------------------------------------
var arbNum = 100;
var fake = [];
var currencyVal = currencyValues[singleArr[2][0]];
var totalOfCurrVal = singleArr[2][1];//2 is Nickel
var test = function(total,totalCurr) {
if (totalCurr === totalOfCurrVal && (total > 0 && total - currencyVal <= 0) || total === 0) {
fake.push([total, currencyVal]);
}
var accum = totalCurr + currencyVal;
var subtract = total - currencyVal;
return test(subtract,accum);
};
return test(arbNum,0);
}
// Example cash-in-drawer array:
// [["PENNY", 1.01],
// ["NICKEL", 2.05],
// ["DIME", 3.10],
// ["QUARTER", 4.25],
// ["ONE", 90.00],
// ["FIVE", 55.00],
// ["TEN", 20.00],
// ["TWENTY", 60.00],
// ["ONE HUNDRED", 100.00]]
checkCashRegister(19.50, 20.00, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.10], ["QUARTER", 4.25], ["ONE", 90.00], ["FIVE", 55.00], ["TEN", 20.00], ["TWENTY", 60.00], ["ONE HUNDRED", 100.00]]);