I saw last days this question about Javascript, that a function should return back some values based on the number of parentheses calls in the function.
console.log(f() == 1); //->true
console.log(f()() == 3); //->true
console.log(f()()() == 6); //->true
... //and so on 10,15,21...
I came up with the following code:
function f() {
f.count++;
return f;
};
f.count=0;
f.toString = function(){
console.log(f.count);
return f.count;
};
console.log(f() == 1); // true
console.log(f()() == 3); //3
console.log(f()()() == 6); //6
But this will break if, for instance, I call:
f();
console.log(f() == 1); // true
console.log(f()() == 3); //3
console.log(f()()() == 6); //6
Which I understand why. However, my question is: how can I make this recursive in the way that the function can tell how many parentheses were used and to be independent of the other calls?
So for instance, when I'm saying f()
to get 1 and if I say f(); f();
to get 1 and 1. Not 1 and 2.
I know that maybe it has to do with the scope of the variable (I was trying to follow this: What is the scope of variables in JavaScript?), but for my example, my tries were without success.