作为编程挑战的一部分,我们的任务是创建一个具有不确定数量的连续调用的函数.举个例子,假设函数只返回提供的参数的总和,它应该如下工作:
sum(4)() // 4 sum(4)(5)() // 9 sum(4)(5)(9)() // 18 sum(4)(5)(9)(1)() // 19 // etc...
我已经开发了一个解决方案来完成工作,但在函数本身内部使用全局变量:
var sum = function (a) { if (!sum.init) { sum.total = 0; sum.init = true; } if (!arguments.length) { sum.init = false; return sum.total; } sum.total += a; return sum; };
这个解决方案有效,但使用状态,全局变量和函数对象技巧,这是不理想的.我的问题是,是否有办法以纯粹的递归方式解决问题.
作为旁注,如果没有提供最后一次空调(),我不相信问题可以解决,但如果我错了请告诉我.
更新
CodeReview中已回答此问题:https://codereview.stackexchange.com/a/153999/129579
解决方法
你可以利用闭包来实现你想要的东西:
function sum(value){ // the closure variable that will be accessible for all the _sum calls (initialised to 0 for every sum call). var result = 0; // the function that will be returned (sum will only get called once to initialize the result to 0. It's _sum which will be returned as much as possible) function _sum(a){ // if we passed a parameter,then add it to result and return a new _sum if(typeof a != "undefined"){ result += a; return _sum; } // if we didn't return the result else return result; } // of course after initializing result we need to call _sum that handle the actual summing and return whatever it returns (if value is defined,it will return another `_sum` if not it will return the value of result which will be 0 at first) from now on sum will have nothing to do with the rest of the calls (()()()... ) return _sum(value); } console.log("sum() = " + sum()); console.log("sum(7)() = " + sum(7)()); console.log("sum(5)(6)(7)() = " + sum(5)(6)(7)()); // will return 0 because we call sum again console.log("sum() = " + sum());
注:总和(1)(7)(3)());将按此顺序致电:
>与参数1相加,将结果初始化为0并调用
> _sum具有相同的参数1,它将把它添加到结果并返回一个新的ins of _sum将被调用,所以以下
> _sum用参数7调用,添加它并返回一个新的_sum所以新的
> _sum用参数3调用,…生成另一个
> _sum将没有参数,因此如果(typeof a!=“undefined”)将失败并且此_sum将返回结果.