javascript: recursive anonymous function?

Viewed 81299

Let's say I have a basic recursive function:

function recur(data) {
    data = data+1;
    var nothing = function() {
        recur(data);
    }
    nothing();
}

How could I do this if I have an anonymous function such as...

(function(data){
    data = data+1;
    var nothing = function() {
        //Something here that calls the function?
    }
    nothing();
})();

I'd like a way to call the function that called this function... I've seen scripts somewhere (I can't remember where) that can tell you the name of a function called, but I can't recall any of that information right now.

21 Answers

Yet another Y-combinator solution, using rosetta-code link (I think somebody previously mentioned the link somewhere on stackOverflow.

Arrows are for anonymous functions more readable to me:

var Y = f => (x => x(x))(y => f(x => y(y)(x)));

I don't suggest doing this in any practical use-case, but just as a fun exercise, you can actually do this using a second anonymous function!

(f => f(f))(f => {
    data = data+1;
    var nothing = function() {
        f();
    }
    nothing(f);
});

The way this works is that we're passing the anonymous function as an argument to itself, so we can call it from itself.

Related