[英]Sum function currying
I'm trying to write a sum function that does the following: 我正在尝试编写一个执行以下操作的求和函数:
sum(1)(2)(3) => returns 6
However, I am having hard time with my solution. 但是,我的解决方案很难。 I know i'm making a silly mistake, can someone point me in the right direction? 我知道我犯了一个愚蠢的错误,有人能指出我正确的方向吗?
My Implementation: 我的实施:
function add(args) { let sum = args[0]; let func = function(...args2) { if (!args2[0]) return sum; sum += args2[0]; return func; } return func; } add(1)(2)(3);
Additionally, can I write a generic function that does the following? 另外,我可以编写一个执行以下操作的通用函数吗? add(1)(2)(3) or add (1)(2)(3) () => 6 add(1)(2)(3)或add(1)(2)(3)()=> 6
To have an arbitrary amount of calls, all which take a number, you'd need the return value to behave both as a function and a number depending. 要获得任意数量的调用,所有调用都需要数字,您需要返回值作为函数和数字依赖。 So that: 以便:
const five = add(2)(3);
console.log(five(10)); // behaves like a function
console.log(five + 10); // behaves like a number
I can't think of anyway to do that (or if there's a good reason one should do that) other than what I'd call a hack. 除了我称之为黑客之外,我无论如何都无法想到这样做(或者如果有一个很好的理由应该这样做)。
With that said, for fun I was able to do the following by abusing valueOf()
: 有了这个说,为了好玩,我能够通过滥用valueOf()
来做到以下几点:
const add = (num1) => { const func = (num2) => add(num1 + num2); func.valueOf = () => num1; return func; } console.log(add(1)(2)(3)); // *logs function* [output varies by environment] console.log(add(1)(2)(3) + 10); // 16 console.log(add(1)(2) + 10); // 13 console.log(add(1) + 10); // 11 console.log(add(1)(2)(3) == 6); // true console.log(add(1)(2)(3) === 6); // false console.log(typeof add(1)(2)(3)); // function console.log(typeof (add(1)(2) + 3)); // number
But that's obviously not very kosher. 但这显然不是非常犹太。
Edit: Switched from using toString()
to valueOf()
per @PatrickRoberts's comment . 编辑:根据@ PatrickRoberts的评论从使用toString()
切换到valueOf()
。
Try this, you omitted the spread operator 试试这个,你省略了扩展运算符
function add(...args) { let sum = args[0]; let func = function(...args2) { if(args2[0] === undefined) return sum; sum += args2[0]; return func; } return func; } console.log(add(1)(2)(3)());
cheers!! 干杯!!
Recursion anyone? 任何人的递归? 😂 😂
function add(n) {
return function(m) {
if (isNaN(m)) return n;
return add(n + m);
};
}
// add(1)(2)(3)() => 6
// add(1)(2)(3)("")() => "6"
// add(1)("2")(3)() => "123"
// functional one liner
const add = n => m => isNaN(m) ? n : add(n + m);
function sum(x){
return function (y){
return function(z){
return x+y+z;
}
}
}
You can call like : sum(1)(2)(3) 你可以这样打电话:sum(1)(2)(3)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.