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

别来无恙 提交于 2019-12-08 08:52:22

问题


I was asked this question in an interview.

for sum(2)(3) in currying style

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

for sum (2, 3)

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

Is there any common function which can work for both


回答1:


Here's a function that can create a generalized curried function from any non-curried function. It is written without using any ECMAScript 6 syntax. This works regardless of the number of parameters expected by the original function, or the number of arguments provided to each partial application.

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



回答2:


There is a way, but it is quite hacky...

You can always check that a second argumet has been passed to your function and react accordingly

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

    return a + b;
}



回答3:


You could return either the sum or a function based on the length of the arguments object.

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



回答4:


You can have a function that does both with infinite currying :

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


来源:https://stackoverflow.com/questions/58191104/sum23-and-sum2-3-what-is-the-common-solution-for-both

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!