Fred J.
Fred J.

Reputation: 6019

Javascript tail recursion instead of loop

In one of Douglas Crockford speeches, He favours the use of tail recursion over loops. this code was presented,

function repeat(myFunc) {
  if (myFunc !== undefined) {
    return repeat(myFunc);
  }
}

I thought to define a myFunc but don't know if a static counter can retain its state during function calls or use a global counter. but being new to javascript I wanted to ask first. How can this be used in an example, say to count down from 10 to 0? Thanks.

Upvotes: 1

Views: 129

Answers (4)

guest271314
guest271314

Reputation: 1

How can this be used in an example, say to count down from 10 to 0?

Pass a Number to repeat, call repeat with decremented number as parameter until variable parameter is equal to 0

function repeat(n) {
  console.log(n)
  if (n) {
    return repeat(--n);
  }
}

repeat(10)

Upvotes: 2

trincot
trincot

Reputation: 350137

Here is a version that keeps state without global variable:

function repeat(myFunc, arg) {
    if ((arg = myFunc(arg)) !== undefined) {
        repeat(myFunc, arg);
    }
}

repeat(function (count) {
    document.write(count + ',');
    count--;
    if (count >= 0) return count;
}, 10);
 

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386560

You need to call the function myFunc somewhere -- and evaluate the result for further call of repeat.

function repeat(myFunc) {
    if (myFunc()) {
        repeat(myFunc);
    }
}

var count = 10;

repeat(function () {
    document.write(count + '<br>');
    count--;
    return count >= 0;
});
 

Upvotes: 3

Oriol
Oriol

Reputation: 288020

Not sure if I understand what approach you want, but you can use this to count down recursively

function repeat(myFunc, times) {
  if(times > 0 && typeof myFunc == 'function') {
    myFunc(times);
    repeat(myFunc, times-1);
  }
}
repeat(alert, 10);

Upvotes: 0

Related Questions