0

Are there any variants to realize add function in JS?

console.log(add(1)(3)(5)(35)); // 44

There can be any number of function calls.

  • Are you looking for "varargs" (a function that can take any number of arguments, like `Math.min`)? – Thilo Sep 28 '15 at 12:05
  • 3
    I don't think you can do this exactly like this in javascript, at the very least you'd need something different on the end, such as `()` rather than another number, to differentiate the fact you've got to the end of the chain. You want to look into [function currying](http://www.crockford.com/javascript/www_svendtofte_com/code/curried_javascript/index.html) – James Thorpe Sep 28 '15 at 12:05
  • Using Ramda, you create a curried function `fnc` that adds its arguments, then pass it to `nAry(4, fnc)`, but you would need to know the length of arguments beforehand. Otherwise, as @JamesThorpe mentioned, you would need to return a thunk – Dan Sep 28 '15 at 12:13
  • On this page http://javascript.info/tutorial/closures you can find a solution for "Create a function sum that will work like that: `sum(a)(b) = a+b` and accepts any number of brackets." – gefei Sep 28 '15 at 12:13
  • 2
    already answered in http://stackoverflow.com/questions/29376702/tail-function-in-javascript/29376983#29376983 – Touffy Sep 28 '15 at 12:14
  • @gefei Note that that solution requires something converting the function to a string and implicitly calling the `toString` function on it. – James Thorpe Sep 28 '15 at 12:15

1 Answers1

0

You can assign a semi private property to the function, something like:

function doSum(sum, reset){
    doSum.sum = reset ? 0 : (doSum.sum || 0);
    doSum.sum += sum || 0;
    return !sum && !reset ? doSum.sum : doSum;
};

// calculate 1 + 2 + 3 + 4
var total   = doSum(1)(2)(3)(4)();

// reset, calculate 10 + 20 + 30 + 40
var total2  = doSum(10,true)(20)(30)(40)();

// continue, calculate total2 + 100 + 100 + 50
var total2a = doSum(100)(100)(50)();

// print result
document.querySelector('#result').textContent =
    'total   = ' + total + '\n' +
    'total2  = ' + total2 + '\n' +
    'total2a = ' + total2a;
<pre id="result"></pre>
KooiInc
  • 119,216
  • 31
  • 141
  • 177