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