How to determine how many functions are being called? (multiple brackets)
Let me suggest an example that works, then follow up on what fails by highlighting the point of view of my question.
Here we have 3 functions called (1, 2 anonymous):
var add = function(a, b) {return a+b};
var multiply = function(a, b) {return a*b};
function myFunction(fxn) {
return function(x) {
return function(y) {
return fxn(x,y);
}
}
}
myFunction(add)(2)(3)
It is clear that this call fails:
myFunction(add)(2)(3)(4)
How do you determine how many functions are being called? In the second call, I call 4 functions (1, 3 anonymous).
How can I rewrite the function myFunction
to accommodate any number of calls? I know that we can determine how many arguments were given by a function, but is there a way to determine how many functions are called? I hope I phrased it correctly. Thank.
source to share
To find out if a variable contains a reference to a function that you can use below the code:
if (typeof(v) === "function") alert("This is a function")
Based on above, you can find out how many nested functions there are
function myFunction() {
return function() {
return function() {
return 1 + 2;
}
}
}
var count = 0;
var v = myFunction();
while (typeof(v) === "function") {
count++;
v = v();
}
alert("Nr of nested functions: " + count)
source to share
Even if it has no practical use that I can think of, this is a possible solution:
var add = function(a, b) {
return a + b
};
var multiply = function(a, b) {
return a * b
};
var counter = 0;
var result = 0;
function myFunction(fxn) {
counter = 1;
result = 0;
return function first(x) {
++counter;
return function second(y) {
++counter;
x = result ? result : x;
result = fxn(x, y);
return second;
}
}
}
myFunction(add)(1)(2)(3)(4);
alert('Result is: ' + result + '; Parentheses count: ' + counter);
source to share