Juan Vazquez
Juan Vazquez

Reputation: 543

Did I use recursion correctly?

I'm working through some practice JavaScript problems, and solved a problem involving recursion. Although I got it right, my implementation is different from the "official" solution, so I was wondering if anyone had any insight on whether the official answer is better and if so, why.

Question

Implement a function that takes a function as its first argument, a number num as its second argument, then executes the passed in function num times.
It's ok to use a loop in your implementation, bonus points if you use recursion instead.

My Solution

function repeat(operation, num) {
    if (num > 0) {
        operation();

        repeat(operation, num - 1);
    };
};

Given Solution

function repeat(operation, num) {
    if (num <= 0)
        return;

    operation();

    return repeat(operation, --num);
};

Is there anything about the given solution that makes it better than mine?

Upvotes: 8

Views: 146

Answers (3)

N. Leavy
N. Leavy

Reputation: 1074

There is a specific reason to directly return the result of a recursive call. This is called "tail recursion", and a clever run-time environment can optimise for that case and execute without using any additional stack space for the recursive calls (it simply reuses the stack space of the current function). In the latest ECMAScipt 6 specification (Javascript to you and me) it specifically calls out that the runtime environment should optimise tail-recursive calls.

In practice, your code does in fact not do anything after the recursive call, so it is properly tail-recursive. Putting the recursive call with a return statement makes it clear that it should be a tail-recursive call, and a bit more likely that the run-time environment will correctly optimise it.

Upvotes: 5

Georgi Naumov
Georgi Naumov

Reputation: 4201

Just bear in the mind. There is something that every JavaScript developer MUST know. If recursion continues very long time the browser can kill your script or alert error to user. Often JavaScript developers uses approaches like this:

var inputArray = [1,2,3,4,5,6];

(function handleArray() {
    var currentElement = inputArray.shift();
    // do something with currentElement 
    if (inputArray.length > 0 ) {
        setTimeout(handleArray, 0);
    }
}()); 

In this way you will break long time operation on small parts.

Upvotes: 5

Tennyson H
Tennyson H

Reputation: 1716

The solutions are identical, but in practice the given solution is easier to understand. There is a clear "base case," and the recursion is done in the return statement. Both of these properties lead to better code quality and readability when dealing with recursive functions.

Upvotes: 4

Related Questions