JavaScript currying function


function add(x) {

  return function(y) {

    return x + y;

  };

}



let add5 = add(5);

console.log(add5(3)); // Output: 8

More complex curry function


function curry(func) {

  return function curried(...args) {

    if (args.length >= func.length) {

      return func.apply(this, args);

    } else {

      return function(...moreArgs) {

        return curried.apply(this, args.concat(moreArgs));

      };

    }

  };

}



function add(a, b, c) {

  return a + b + c;

}



const curriedAdd = curry(add);



console.log(curriedAdd(1)(2)(3)); // Outputs: 6

console.log(curriedAdd(1, 2)(3)); // Outputs: 6

console.log(curriedAdd(1)(2, 3)); // Outputs: 6

console.log(curriedAdd(1, 2, 3)); // Outputs: 6

Leave a Comment