SJC
SJC

Reputation: 107

How to keep a count of how many times a function which returns itself has been called?

My question is, if I have a function like this

function f(a) {
if (a == undefined) {
    alert(1)
    return f
} else {
    alert(2)
}

}

and I call it like this, for example, f()()()()('123'), how can I keep track of how many times f was called?

Edit: I had a play around and worked out a solution:

function f(a) {
if (!f.count) {
    f.count = 0;
}
if (a == undefined) {
    alert(1);
    ++f.count;
    return f;
} else {
    f.count = 0;
    alert(2);
}

}

alert(1) and alert(2) are essentially placeholders for the moment. The count variable would be used in the else section in the actual function. Thank you all for your help.

Upvotes: 0

Views: 94

Answers (3)

Faisal
Faisal

Reputation: 139

By "wrapper function) do you mean "closure"?

var f = (function (a) {
  var count = 0; 

  return function () { 
    console.log(count);
    count += 1;

    if (!a) {
      alert(1);
      return f;
    } else {
      alert(2);
    }
  }

})();

Upvotes: 0

user1329482
user1329482

Reputation: 569

Rather than pollute the global space, attach the counter to the function itself.

function f(a)
{
    ++f.counter;
    if (a) {
       doAThing();
       return f;
    } else 
       doAnotherThing();
}
f.counter = 0;

Now you can access the number of calls by evaluating f.counter at any point.

Upvotes: 2

Basti
Basti

Reputation: 731

Just create a count variable outside of the function scope and whenever you enter the function, you increase its value.

var count = 0;

function f(a) {
    count++;

    if (!a) {
        alert(1);
        return f;
    } else {
        alert(2);
    }
}

Upvotes: 1

Related Questions