Skip to content

Instantly share code, notes, and snippets.

@jokester
Last active October 21, 2016 23:07
Show Gist options
  • Save jokester/e9a7e3a97b55b42f08f9 to your computer and use it in GitHub Desktop.
Save jokester/e9a7e3a97b55b42f08f9 to your computer and use it in GitHub Desktop.
curry in javascript
var curry = function(foo, arity) {
var curried = function() {
// parameters by far are passed with `this`
// slice()-ing it here makes the curried function stateless
var new_args = this.slice();
for(arg_key in arguments) {
new_args.push(arguments[arg_key]);
}
if (new_args.length >= arity) {
return foo.apply(null, new_args);
} else {
return curried.bind(new_args);
}
};
return curried.bind([]);
};
var sum4 = function(a,b,c,d) { return a+b+c+d; };
var curried = curry(sum4, sum4.length);
console.log(curried(1,2,3)(4));
// -> 10
console.log(curried(1)(2,3)(4));
// -> 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment