sum(2)(3) 和 sum(2, 3) 两者的共同解决方案是什么

sum(2)(3) and sum(2, 3) what is the common solution for both

我在面试中被问到这个问题。

sum(2)(3) 柯里化风格

sum(a) {
  return (b) {
    return a + b;
  }
}

总和 (2, 3)

sum(a, b) {
  return a + b;
}

是否有任何共同的功能可以同时适用于两者

有一个方法,但是很hacky...

您始终可以检查第二个参数是否已传递给您的函数并做出相应反应

function sum(a, b){
    if(b === undefined){
        return (c) => {
            return c + a;
        }
    }

    return a + b;
}

您可以 return 基于 arguments 对象的 length 的总和或函数。

function sum(a,b) {
  return arguments.length === 2   //were two arguments passed?
    ? a+b                         //yes: return their sum
    : (b) => a+b                  //no:  return a function
};

console.log(sum(3)(5));
console.log(sum(3,5));

这是一个可以从任何非柯里化函数创建广义柯里化函数的函数。它是在不使用任何 ECMAScript 6 语法的情况下编写的。无论原始函数期望的参数数量或提供给每个部分应用程序的参数数量如何,这都有效。

function sum (a, b) {
  return a + b;
}

function product (a, b, c) {
  return a * b * c;
}

function curry (fn) {
  return function partial () {
    return arguments.length >= fn.length
      ? fn.apply(this, arguments)
      : partial.bind.apply(partial, [this].concat(Array.prototype.slice.call(arguments)));
  };
}

var s = curry(sum);

console.log(s(1, 2));
console.log(s(1)(2));
console.log(s()()(1)()()(2));

var p = curry(product);

console.log(p(2, 3, 4));
console.log(p(2)(3)(4));
console.log(p()()(2)()()(3, 4));

你可以有一个函数来无限柯里化:

the idea here is to return a function as well as a computed value each time, so that if it is called again, the returned function will handle it, and if its not called, the computed value is printed.

function sum(...args) {
  function add(...args2) {
    return sum(...args, ...args2);
  }

  const t = [...args].reduce((acc, curr) => acc + curr, 0);
  add.value = t;

  return add;
}

const result1 = sum(2, 3).value;
const result2 = sum(2)(3).value;
const result3 = sum(2, 3)(4).value;
const result4 = sum(2, 3)(4, 5).value;
const result5 = sum(2, 3)(4, 5)(6).value;

console.log({ result1, result2, result3, result4, result5 });

你必须检查是否定义了第二个参数:

const sum = (a,b) => {
  const add1 = (b) => {
      return a+b
  }

return typeof b == 'undefined' ? add1 :   add1(b)   \if it has the second arg else if it hasn't the second arg so give it the arg\

}