Last active
June 4, 2016 15:12
-
-
Save vividness/9284075 to your computer and use it in GitHub Desktop.
A sloppy example on JavaScript curry function
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
/** | |
* A sloppy example on JavaScript curry function | |
* | |
* @author Vladimir Ivic <[email protected]> | |
* @github http://github.com/mancmelou | |
*/ | |
/** | |
* Here we are, the curried function definition | |
*/ | |
var add = function (a, b) { | |
if (a === undefined && b === undefined) { | |
// in case no args are passed return the function | |
return add; | |
} else if (b === undefined) { | |
// if the last parameter is omitted, return a new | |
// function that will call the original function | |
return function (b) { | |
return add(a, b); | |
}; | |
} else { | |
// all parameters here; good; perform | |
return a + b; | |
} | |
}; | |
/** | |
* Some usage examples | |
*/ | |
// example 1. immediate call | |
add(3, 4) === 7; | |
// example 2. immediate call with the split parameters | |
add(3)(4) === 7; | |
// example 2. intermediate call. | |
// call function when we know the first param, then do some other | |
// processing and then call it again when the second param is known | |
var added_3 = add(3); | |
console.log("Doing something else..."); | |
console.log("Doing something else..."); | |
console.log("Ok, time to finish the add() operation..."); | |
added_3(4) === 7; | |
// example 3. not a real world usage example though | |
add()()()()()()(3)(4) === 7; | |
add(3)()()()()()(4) === 7; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment