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

问题描述 投票:0回答:6

我在采访中被问到这个问题。

对于咖喱风格的

sum(2)(3)

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

求和 (2, 3)

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

有没有什么共同的功能可以同时使用

javascript currying
6个回答
3
投票

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

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

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

function curry (fn) {
  return function partial () {
    if (arguments.length >= fn.length) {
      return fn.apply(this, arguments);
    }

    var partialArgs = Array.prototype.slice.call(arguments);
    var bindArgs = [this].concat(partialArgs);
    return partial.bind.apply(partial, bindArgs);
  };
}

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));


2
投票

有一种方法,但它很hacky...

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

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

    return a + b;
}

2
投票

您可以返回总和或基于

length
 对象的 
arguments
的函数。

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));


0
投票

您可以拥有一个可以同时进行无限柯里化的函数:

这里的想法是每次返回一个函数和一个计算值,这样如果再次调用它,返回的函数将处理它,如果没有调用,则打印计算值。

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 });


0
投票

您必须检查第二个参数是否已定义:

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\\

}


0
投票

希望对你有帮助

    const sum =(a,b)=>{
      return a.reduce((pre,cur)=> pre + cur , b)
    }
    const add=(...a)=> (...b)=> b.length ? add(sum(b,sum(a,0))) : sum(a,0)
    
    console.log(add(2,3,4)(5)(2)(8,6,3,5)())
    console.log(add(2,3,4,5,2,8,6,3,5)())

© www.soinside.com 2019 - 2024. All rights reserved.