Reputation: 49
Please, help needed! I'm trying to make a small js compounding calculator
function calculateCompound(amount, earning, remains, roi, compound) {
if (remains > 0) {
var ini_earning = earning;
var accrual = amount * roi;
earning = accrual * (1 - compound);
var new_amount = amount + accrual - earning;
var new_earning = ini_earning + earning;
remains--;
calculateCompound(new_amount, new_earning, remains, roi, compound);
}
return earning + amount;
}
calculateCompound(100, 0, 5, .1, .5);
but after 5 calls it returns the initial values (105 in this case)
Many thanks in advance!
Upvotes: 1
Views: 318
Reputation: 10849
The you never return the value from your recursion call, this is why it returns the initial value.
The idea is to have a base case which returns earning + amount
And recur by returning the calculateCompound
call value
function calculateCompound(amount, earning, remains, roi, compound) {
if (remains <= 0) {
return earning + amount;
}
var ini_earning = earning;
var accrual = amount * roi;
earning = accrual * (1 - compound);
var new_amount = amount + accrual - earning;
var new_earning = ini_earning + earning;
return calculateCompound(new_amount, new_earning, remains - 1, roi, compound);
}
Upvotes: 2