[SOLVED] Potential issues for recursive function not being called in another function

Issue

I’m trying to build a cash register (an algorithm project in FreeCodeCamp) and I’ve created a function (giveChange(), a recursive function) to be invoked in another separate function (checkCashRegister).

However, the function is not being called. I would like function checkCashRegister to return 0 in my case.

I checked whether it’s the problem of placing "return" in the wrong place in for loop or problems of scope. Doesn’t seem either.

``````function giveChange(diff, cid) {
for(let i = cid.length - 1; i > 0; i--) {
if(cid[i-1][0] <= diff && diff <= cid[i][0]) {
diff = diff - Math.min(cid[i-1][1], cid[i-1][0]*Math.ceil(((diff-cid[i-1][0])/cid[i-1][0])))
if(diff !== 0) {
giveChange(diff, cid)
} else {
return diff
}
}
}
return diff
}

function checkCashRegister(price, cash, cid) {

let diff = cash - price
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

giveChange(diff, cid)

return diff
}

checkCashRegister(3.26, 100, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]])
``````

Solution

You are missing `return` keyword before invoking `givechange(diff, cid)`,

Note: I’ve updated the condition and used a ternary to not repeat the `return` keyword

``````function giveChange(diff, cid) {
for (let i = cid.length - 1; i > 0; i--) {
if (cid[i - 1][0] <= diff && diff <= cid[i][0]) {
diff = diff - Math.min(cid[i - 1][1], cid[i - 1][0] * Math.ceil(((diff - cid[i - 1][0]) / cid[i - 1][0])))
return diff !== 0 ? giveChange(diff, cid) : diff
}
}
console.log(diff)
return diff
}

function checkCashRegister(price, cash, cid) {

let diff = cash - price
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

return giveChange(diff, cid)
}

checkCashRegister(3.26, 100, [
["PENNY", 1.01],
["NICKEL", 2.05],
["DIME", 3.1],
["QUARTER", 4.25],
["ONE", 90],
["FIVE", 55],
["TEN", 20],
["TWENTY", 60],
["ONE HUNDRED", 100]
])``````

Answered By – dippas

Answer Checked By – Mary Flores (BugsFixing Volunteer)