咖喱javascript sum函数. [英] Curried javascript sum function.

查看:40
本文介绍了咖喱javascript sum函数.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个有趣的问题.编写一个javascript函数,该函数通过多次调用同一函数来返回传递给它的所有参数的总和.

I came across this interesting problem. Write a javascript function that returns sum of all the arguments passed to it, through multiple calls to that same function.

以下是调用函数的方法-

Here are the ways function can be called -

sum(1, 2, 3, 4);
sum(1, 2)(3, 4);
sum(1, 2)(3)(4);
sum(1, 2, 3)(4);
sum(1)(2, 3, 4);

上面的所有调用均应正常工作并返回10.

All the calls above should work and return 10.

这是我到目前为止编写的内容,但仅适用于前两个函数调用 sum(1、2、3、4) sum(1、2)(3,4),然后将其搁在床上.

Here's what I have written so far, but it only works for first two function calls sum(1, 2, 3, 4) and sum(1, 2)(3, 4) and shits the bed for rest of it.

const arr = [];

function sum(...args) {
  if (args.length === 4) {
    return args.reduce((acc, curr) => {
      return (acc = acc + curr);
    }, 0);
  } else {
    arr.push(...args);
    return function(...args) {
      arr.push(...args);
      return sum(...arr);
    };
  }
}

请有人帮我,这真让我发疯.

Someone please help me, this is driving me nuts.

谢谢!

推荐答案

您非常接近.这是使用 .bind 方法返回一个函数,该函数可以捕获第一个参数(如果您尚未获得至少四个参数的话).

You're pretty close. This is a perfect opportunity to use the .bind method to return a function that captures the first arguments if you haven't yet been given at least four.

所以像这样:

function sum(...args) {
  if (args.length >= 4) {
    return args.reduce((acc, curr) => {
      return (acc = acc + curr);
    }, 0);
  } else {
    // Bind the arguments you have to this function, and return it:
    return sum.bind(null, ...args)
  }
}

console.log(sum(1, 2, 3, 4));
console.log(sum(1, 2)(3, 4));
console.log(sum(1, 2)(3)(4));
console.log(sum(1, 2, 3)(4));
console.log(sum(1)(2, 3, 4));

最后,我将更改条件以检查> = 4 ,这样,超过此限制不会导致您永远咖喱.

Finally, I'd change the condition to check for >= 4 so that passing more than that doesn't result in a case where you'll curry forever.

这篇关于咖喱javascript sum函数.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆