Last active
September 24, 2015 05:19
-
-
Save jamischarles/3c22acd58e6d4ab26a41 to your computer and use it in GitHub Desktop.
A simple example of currying in JS
This file contains hidden or 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 is a 'curried' function. If it receives less params than it expects, it returns a function which expects the rest of the params. | |
function add(a, b) { | |
// if 2nd param wasn't passed, return a function that holds the 1st param via closure, but expects another param. | |
if (typeof b === "undefined") { | |
return function(c) { | |
a + c; | |
} | |
} | |
// if 2 params are passed return the result | |
return a + b; | |
} | |
add(2,2); | |
// 4 | |
// we are now using the curried function | |
add(1)(2); | |
// 3 | |
// and we can do this... | |
var add2 = add(2); | |
add2(3); | |
// 5 | |
// some more reading here: | |
// https://javascriptweblog.wordpress.com/2010/04/05/curry-cooking-up-tastier-functions/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment