javascriptcurrying

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


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


Solution

  • 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 () {
        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));