Make a function supporting currying AND traditional multiple parameters

Question: How would you do 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 will be implemented as follows:

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

and the second is a normal function:

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

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

+4
source share
2 answers

You can use a higher order function to port other functions with this behavior.

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

curry , , . , originalFunction. , ,

Function#length , .

function curry (fn) {
  return function (...args) {
    if (args.length >= fn.length) {
      return fn.call(this, ...args)
    } else {
      return curry(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
+2

:

function add(a, b) {
  if (arguments.length == 2) {
    return a + b;
  }
  return function(b) {
    return add(a, b);
  }
}

console.log(add(2)(5)); // 7
console.log(add(2, 5)); // 7
+2

Source: https://habr.com/ru/post/1668889/


All Articles