Skip to content

Instantly share code, notes, and snippets.

@thaibui
Created March 24, 2016 01:23
Show Gist options
  • Save thaibui/b919fdba331488cb378e to your computer and use it in GitHub Desktop.
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)
/**
* 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