-
-
Save getify/b1435aa3b419f89d1f9c to your computer and use it in GitHub Desktop.
| function spread(fn) { | |
| return function(args){ | |
| fn.apply(null,args); | |
| }; | |
| } | |
| // ****************** | |
| function foo(x,y) { | |
| console.log(x,y); | |
| } | |
| spread(foo)([10,20]); // 10 20 | |
| // Trying to find the Functional equivalent to `spread(..)` | |
| // Something like: | |
| Function.apply.bind(foo)([10,20]); // undefined undefined | |
| // see, that doesn't quite work. help? |
So, if I have:
function plus (a, b) { return a + b; }
You want function spread such that:
spread(plus)([2,3])
//=> 5
But, you want to formulate it in some kind of point-free form, rather than as a function that returns a first-class function. Like maybe:
Function.apply.bind(plus, null)([1, 2])
//=> 3
Ahh, perfect. I knew I was close. Of course, that makes sense. The null has got to pass thru into the apply(..). Duh. :) Thanks!
@getify @raganwald Can you guys explain this. Unable to understand this. I understood the problem statement. But why din't it work and how did it work after passing null to the bind method?
Function.bind() allows to execute .apply() in the context of the spread / plus function (pretty much the same as plus.apply() ).
The first argument of .apply() defines the context .apply() should execute in, the second are the actual parameters as an array ( fn.apply(context, args ).
So this should also work:
Function.apply.bind(plus)(null, [1,2])
But that is not as nice.
Function.bind() also allows partial application with predefined arguments:
var plusOne = plus.bind(window, 1);
console.log(plusOne(2)); // 3
They are using this to partially apply the null value as the context for .apply()
Does this not do what you want?
EDIT: Per your Tweet, no ;) "I want a function i can pass the array [1,2] to and it automatically applies/spreads it to
foo(..)"