Mhd.Tahawi Mhd.Tahawi - 4 years ago 101
Javascript Question

Make function that supports currying AND the traditional multiple parameters


Question: How would you make this work?

add(2)(5); // 7

add(2, 5); // 7


I am trying to solve the question above:
I know that the first solution uses currying and would be implemented as follows:

var add = functoin(x){
return function (y){
return x+y;
};
};


while the second is jsut your normal function:

var add = functoin(x,y){
return x+y;
};


Is there a way to make both work at the same time?

Answer Source

You can use a higher-order function to wrap other functions with that behaviour.

This kind of function is often called curry, and it comes with many libraries (lodash, for example).

curry returns a new function that checks whether all the expected arguments have been supplied. If they have, it calls originalFunction. If not, it returns a partially applied function,

This implementation uses Function#length to test call arity, so it works with any number of arguments.

function curry (fn) {
  return function (...args) {
    if (args.length >= fn.length) {
      return fn.call(this, ...args)
    } else {
      return fn.bind(this, ...args)
    }
  }
}

function add (x, y) {
  return x + y;
}

// You can curry any function!
const curriedAdd = curry(add);

console.log(curriedAdd(1, 2)); // 3
console.log(curriedAdd(1)(2)); // 3
console.log(curriedAdd(1));    // a function

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download