Reputation: 1368
I have a function that I cannot modify and I need to call it, but I haven't seen something like this before.
var myCategorize = function(z) {
return function(q) {
return 1;
}
}('window'.indexOf('w') > 0 || window || false);
I have stripped out some of the code in the function(q) portion, just to simplify.
I think I have a curried function, so I tried this:
let category = myCategorize(bookTitles[i])(categories);
but when I do this I get the following error:
Uncaught TypeError: myCategorize(...) is not a function
So maybe this is an anonymous constructor function, so I try something like this:
let category = function(){myCategorize(bookTitles[i])(categories)};
console.log(category.apply());
I get the same error. How do I call this function and get the return value of 1?
Upvotes: 0
Views: 61
Reputation: 28959
myCategorize
is not a curried function, it's an IIFE implementing the module pattern. The brackets at the very end of the last line execute the top-level function(z)
:
var myCategorize = function(z) {
return function(q) {
return 1;
}
}('window'.indexOf('w') > 0 || window || false);
//^--------------------------------------------^
and pass in the value of z
. It's clearer if I re-write it to add extra brackets and names bit:
var myCategorize = (function outer(z) {
//start of outer --^
return function inner(q) {
return 1;
}
})('window'.indexOf('w') > 0 || window || false);
//^-- end of outer
So what you have assigned to myCategorize
is just inner
. To execute it, simply add the brackets and a parameter:
var myCategorize = function(z) {
return function(q) {
return 1;
}
}('window'.indexOf('w') > 0 || window || false);
console.log("myCategorize", myCategorize);
var executionResult = myCategorize("foo");
console.log("executionResult", executionResult);
Upvotes: 2
Reputation: 17654
It's already calling the function once when adding the parenthesis, so the value of myCategorize
is :
ƒ (q) {
return 1;
}
Then you call that function with let category = myCategorize(bookTitles[i])
and the value of category
is : 1
so, then equivalent of let category = myCategorize(bookTitles[i])(categories);
is
let category = 1(categories);
which throws that error
var myCategorize = function(z) {
return function(q) {
return 1;
}
}('window'.indexOf('w') > 0 || window || false);
let category = myCategorize('x'); // 1
console.log(category);
let category2 = myCategorize('x')('y'); // throws, equovalent to 1('y');
Upvotes: 1