Tail in javascript

I want to create a function that adds arguments. The call to this function should be

functionAdd(2)(3)(4)...(n); 

And the result is 2 + 3 + 4 ... + n I'm trying this

 function myfunction(num){ var summ =+ num; if(num !== undefined){ return myfunction(summ); } }; 

But this does not work, ovwerflow error. And I don’t understand where I have to exit this function,

0
source share
2 answers

You can use .valueOf to do the trick:

 function myfunction(sum){ var accum = function(val) { sum += val; return accum; }; accum.valueOf = function() { return sum; }; return accum(0); }; var total = myfunction(1)(2)(3)(4); console.log(total); // 10 

JSFiddle: http://jsfiddle.net/vdkwhxrL/

How it works:

at each iteration, you return a link to the battery function. But when you request the result, .valueOf() is called, which returns a scalar value.

Note that the result is still a function. Most importantly, this means that it is not copied when assigned:

 var copy = total var trueCopy = +total // explicit conversion to number console.log(copy) // 10 ; so far so good console.log(typeof copy) // function console.log(trueCopy) // 10 console.log(typeof trueCopy) // number console.log(total(5)) // 15 console.log(copy) // 15 too! console.log(trueCopy) // 10 
+4
source

If the last call can be without arguments:

 function add(value) { var sum = value; return function add(value) { if(typeof value === 'number') { sum += value return add } else { return sum } } } console.log(add(1)(2)(3)(0)()) // 6 
0
source

Source: https://habr.com/ru/post/985772/


All Articles