Last active
August 29, 2015 14:11
-
-
Save DannyMoerkerke/0f5e752cfc680752a57b to your computer and use it in GitHub Desktop.
Currying in just 6 lines of Javascript code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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