I wanted to try out recursion to calculate compounding interest rather than a loop.
In Ruby:
def compound balance, percentage
balance + percentage / 100 * balance
end
def invest amount, years, rate
return amount if years == 0
invest compound(amount, rate), years - 1, rate
end
This works fine. $10,000 after 1 year at 5% is $10,500; after 10 years, $16,288.
Now the same logic in JavaScript (ES6).
function compound(balance, percentage) {
return balance + percentage / 100 * balance;
}
function invest(amount, years, rate) {
if (years === 0) {
return amount;
} else {
invest(compound(amount, 5), years - 1, rate);
}
}
This returns undefined, but I can't figure out why. It's calling invest the correct number of times, with the correct parameters, and the logic is the same. The compound function works, I tested that separately. So... what could be wrong?