Created
March 24, 2016 01:23
-
-
Save thaibui/b919fdba331488cb378e to your computer and use it in GitHub Desktop.
A Javascript function that does recursive sum and has funny syntax (e.g. sum(3)(5)(-1)() // result 7)
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 function that takes an abitrary number of parameters of the form sum(param1)(param2)(param3)...(paramN)() | |
* and return the total sum = param1 + param2 + .. + paramN. | |
* | |
* Note that the last parameter has to be empty. Thus, sum() is zero. | |
**/ | |
var sum = function(param) { | |
var total = 0; | |
var recursiveSum = function(p) { | |
if( null == p ) { | |
return total; | |
} | |
total += p; | |
return recursiveSum; | |
} | |
return recursiveSum(param); | |
} | |
console.log(sum(-1)(3)(7)()) // output 9 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment