Tail function in javascript [duplicate]

你离开我真会死。 提交于 2019-12-20 06:24:38

问题


I want to make a function which adds arguments. Invoking this function should be

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

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

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

};

But it doesn't works, an error of ovwerflow. And I don't understand where I should out from this function;


回答1:


You can use the .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:

on every iteration you return a reference to the accumulator function. But when you request for the result - the .valueOf() is invoked, that returns a scalar value instead.

Note that the result is still a function. Most importantly that means it is not copied on assignment:

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



回答2:


If 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


来源:https://stackoverflow.com/questions/29376702/tail-function-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!