[英]how to write a sum function with infinite number of arguments, using currying in javascript?
I have tried writing the below code to find sum of 'n' numbers using sum function. 我尝试编写以下代码,以使用sum函数查找'n'个数字的总和。 I am getting the correct response in output . 我在输出中得到正确的响应。 But i am unable to return that using sum function, as i always have to return a function, which is required for curried effect. 但是我无法使用sum函数返回该函数,因为我总是必须返回一个函数,这对于咖喱效果是必需的。
Please help. 请帮忙。 Thanks in advance. 提前致谢。
var output = 0, chain; function sum() { var args = Array.prototype.slice.call(arguments); output += args.reduce(function(a, b) { return a + b; }); sumCurried = sum.bind(output); sumCurried.val = function() { return output; } return sumCurried; } debugger; document.getElementById('demo').innerHTML = sum(1, 2)(3)(4); // document.getElementById('demo').innerHTML = sum(1)(3)(4);
<p id='demo'></p>
enter code here
You can add a stop condition to the curried function, for example - if the function is called without an argument return the output: 您可以向curried函数添加停止条件,例如-如果调用该函数时不带参数,则返回输出:
var output = 0, chain; function sum() { var args = Array.prototype.slice.call(arguments); if(args.length === 0) { return output; } output += args.reduce(function(a, b) { return a + b; }); sumCurried = sum.bind(output); return sumCurried; } console.log(sum(1, 2)(3)(4)());
<p id='demo'></p>
The returned curry function has a val
property, which is a function that returns the current value: 返回的curry函数具有val
属性,该属性是一个返回当前值的函数:
var output = 0, chain; function sum() { var args = Array.prototype.slice.call(arguments); output += args.reduce(function(a, b) { return a + b; }); sumCurried = sum.bind(output); sumCurried.val = function() { return output; } return sumCurried; } console.log(sum(1, 2)(3)(4).val());
<p id='demo'></p>
Why would you use currying at all? 你为什么要用咖喱呢? However, here is a shorter version: 但是,这是一个较短的版本:
const sum = (...args) => {
const func = (...s)=> sum(...args,...s);
func.value = args.reduce((a,b)=>a+b,0);
return func;
};
//usable as
sum(1,2).value,
sum(1,1)(1).value,
sum(1,1)(1,1)(1,1).value
And you always need to end the currying chain. 而且,您始终需要终止可循环链。 However, it can be shortified: 但是,可以将其简化:
func.valueOf = ()=> args.reduce((a,b)=>a+b,0);
//( instead of func.value = ... )
So when called you can do: 因此,在调用时,您可以执行以下操作:
+sum(1,2,3)
+sum(1)(1)(1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.