I have tried writing the below code to find sum of 'n' numbers using sum function. 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.
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:
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:
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.