Reputation: 95
im trying to understand this code for long time i know currying function but confused with this code please explain theory behind
var currying = function(fn) {
var args = [];
return function() {
if (!!arguments.length){
[].push.apply(args, arguments);
return arguments.callee;
} else {
// what is 'this' in apply method
return fn.apply(this, args);
}
}
}
// currying var or args
// please explain the code below
var find = function(arr, el){
return arr.indexOf(el) !== -1;
}
var newFind = currying(find)([1,2,3]);
console.log( newFind(1)());
console.log( newFind(2)());
Upvotes: 0
Views: 264
Reputation: 1012
To make it easier to explain, let's convert the last part of the code:
// newFind = currying(find)([1,2,3]);
// console.log(newFind(1)());
// above is the same with below
console.log( currying(find)([1,2,3])(1)());
currying
takes a function find
so fn
in currying
is find
.
As it return a function, it can be called as it's shown on the code currying(find)([1,2,3])
let's look at this part, currying(find)([1,2,3])
.
It executes the returned method of currying
. It can access the arguments with keyword arguments
that is the array of [1,2,3]
on the code.
The argument is the array which means it has the length value. Then the arguments is pushed into args
array and return its callee which means inner method of currying
.
As it returns method again, it can be called again with next paramter (1)
of currying(find)([1,2,3])(1)()
.
Again, it executes the inner method of currying
with arguments: 1
. Then it is not an array so, it calls fn.apply(this, args)
.
this
keyword in the code means nothing in this case. you can replace this
to null
or you can use fn(...args)
instead. the code is for converting array of argumnts to each argument. e.g. [[1,2,3], 1]
is converted to [1,2,3], 1
Then, finally it executes find
function with parameter [1,2,3]
, 1
. You should remember all this thing is from returned method of currying
so, you must call it as a function. append ()
at the end to execute the function.
Upvotes: 2