recursion - Tail function in javascript -


this question has answer here:

i want make function adds arguments. invoking function should

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

and result 2+3+4...+n i'm trying this

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

but doesn't works, error of ovwerflow. , don't understand should out function;

you can use .valueof 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 works:

on every iteration return reference accumulator function. when request result - .valueof() invoked, returns scalar value instead.

note result still function. importantly means not copied on assignment:

var copy = total var truecopy = +total   // explicit conversion number  console.log(copy)       // 10 ; far 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 

Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -