Gha*_*chi 8 javascript functional-programming
作为编程挑战的一部分,我们的任务是创建一个具有不确定数量的连续调用的函数.举个例子,假设函数只返回提供的参数的总和,它应该如下工作:
sum(4)() // 4
sum(4)(5)() // 9
sum(4)(5)(9)() // 18
sum(4)(5)(9)(1)() // 19
// etc...
Run Code Online (Sandbox Code Playgroud)
最后允许的空函数调用将问题简化为呼叫结束的指示.
我已经开发了一个解决方案来完成工作,但在函数本身内部使用全局变量:
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;
};
Run Code Online (Sandbox Code Playgroud)
这个解决方案有效,但使用状态,全局变量和函数对象技巧,这是不理想的.我的问题是,是否有办法以纯粹的递归方式解决问题.
作为旁注,如果没有提供最后一次空调(),我不相信问题可以解决,但如果我错了请告诉我.
更新
CodeReview已回答了这个问题:https://codereview.stackexchange.com/a/153999/129579
一种不依赖于全局范围且纯功能的neet解决方案.
您可以利用闭包来实现您想要的目标,如下所示:
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());
Run Code Online (Sandbox Code Playgroud)
注意:这sum(1)(7)(3)());
将按以下顺序调用:
sum
1
带有将初始化result
并0
调用的参数_sum
使用相同的参数1
将其添加到result
并返回一个新的实例,_sum
该实例将被调用,因此以下_sum
使用参数调用7
,添加它并返回一个新的,_sum
所以新的_sum
使用参数调用3
,...产生另一个_sum
它将没有参数,因此if(typeof a != "undefined")
会失败,并且_sum
会返回result
。实际sum
只在开始时调用一次做初始化。正如我所说,_sum
从那以后一直到最后都会被束缚。