简体   繁体   English

保持状态处于咖喱状态

[英]Keeping state in curried function

Is there a way to keep some sort of internal state while writing a curried function? 编写咖喱函数时,有没有办法保持某种内部状态?

For example, let's say I want to write a curried function that takes into account the number of times the function was called previously. 例如,假设我要编写一个咖喱函数,该函数考虑到该函数先前被调用的次数。

Ie addProgressively(3)(4)(5) = 1*3 + 2*4 + 3*5 = 26. 即addProgressively(3)(4)(5)= 1 * 3 + 2 * 4 + 3 * 5 = 26。

My approach is to add some counter that increments every time a new curried function is returned but I can't find a good way to keep track of that argument within the addProgressively function. 我的方法是添加一些每次返回新的咖喱函数时都会递增的计数器,但是我找不到在addProgressively函数中跟踪该参数的好方法。

You could use another variable as closure for the factor. 您可以使用另一个变量作为因子的闭合值。

 function addProgressively(x) { var factor = 1, sum = factor * x; function f(y) { factor++; sum += factor * y; return f; }; f.toString = function () { return sum; }; return f; } console.log(addProgressively(3)(4)(5)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM