1

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!

7
  • thanks for formatting the code, I'm pretty new to SO Commented Aug 26, 2015 at 19:12
  • What is the expected value? I'm not familiar with calculating compound Commented Aug 26, 2015 at 19:13
  • Are you missing a return before the internal calculateCompound(...)? Commented Aug 26, 2015 at 19:15
  • But should I? I came from PHP, there you can return from everywhere. Commented Aug 26, 2015 at 19:17
  • 1
    Just look at the function, you are returning earning + amount. Now look before the return call, never mind the recursive call... is there anything modifying earning or amount before the return? No. Hence it will return always the sum of the values passed down to earning and amount when you made the initial function call. Commented Aug 26, 2015 at 19:23

1 Answer 1

2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.