Skip to content

Instantly share code, notes, and snippets.

@getify
Last active August 29, 2015 14:07
Show Gist options
  • Select an option

  • Save getify/b1435aa3b419f89d1f9c to your computer and use it in GitHub Desktop.

Select an option

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?
@dotproto
Copy link

Does this not do what you want?

foo.apply(null, [10, 20]);

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(..)"

@raganwald
Copy link

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

@getify
Copy link
Author

getify commented Oct 19, 2014

Ahh, perfect. I knew I was close. Of course, that makes sense. The null has got to pass thru into the apply(..). Duh. :) Thanks!

@bvjebin
Copy link

bvjebin commented Oct 19, 2014

@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?

@chmanie
Copy link

chmanie commented Oct 19, 2014

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()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment