Skip to content

Instantly share code, notes, and snippets.

@DannyMoerkerke
Last active August 29, 2015 14:11
Show Gist options
  • Save DannyMoerkerke/0f5e752cfc680752a57b to your computer and use it in GitHub Desktop.
Save DannyMoerkerke/0f5e752cfc680752a57b to your computer and use it in GitHub Desktop.
Currying in just 6 lines of Javascript code
// this helper function takes as argument the function that will be curried
function curry(func) {
return function accumulator() {
var args = [].slice.call(arguments);
return args.length < func.length ? accumulator.bind.apply(accumulator, [null].concat(args)) : func.apply(null, args);
};
}
// Use it: first create two function that will be curried
function add(a,b,c) {
return a + b + c;
}
function greet(greeting, name) {
return [greeting, name].join(' ');
}
// curry greet()
var curryGreet = curry(greet);
var sayHi = curryGreet('Hi');
console.log(sayHi('Danny')); // Hi Danny
// curry add()
var curryAdd = curry(add);
var add2 = curryAdd(1,2);
console.log(add2(3)); // 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment