Implement curry function

You are required to implement a curry function that takes a function and returns a curried version of it.

Currying is a technique in functional programming where a function with multiple arguments is broken down into a sequence of functions each taking a single argument.

Currying is a powerful tool that can improve code reusability, composability, and maintainability.

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

let curriedSum = curry(sum);

console.log(curriedSum(1)(2)(3)); // 6
console.log(curriedSum(1, 2)(3)); // 6
console.log(curriedSum(1, 2, 3)); // 6

Use cases and Examples

Convert function into a simple curried function

This is a normal function

const sum = (a, b, c) => {
  return a + b + c;
}

console.log(sum(1, 2, 3)); // Output: 6

Let's transform this function into a curried version:

const sum = (a) => {
  return (b) => {
    return (c) => {
      return a + b + c;
    };
  }
}

console.log(sum(1)(2)(3)); // Output: 6

Advanced curry implementation


function curry(func) {
  // Return a curried version of the original function
  return function curried(...args) {
    // If the number of arguments provided is equal to or greater than
    // the original function's length, invoke the original function
    if (args.length >= func.length) {
      return func.apply(this, args);
    } else {
      // Otherwise, return a function that takes more arguments and
      // combines them with the previous arguments
      return function(...moreArgs) {
        return curried.apply(this, args.concat(moreArgs));
      };
    }
  };
}

// Example usage:
function add(a, b, c) {
  return a + b + c;
}

const curriedAdd = curry(add);

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

Summary

  • Currying transforms a function expecting multiple arguments into a sequence of functions, each taking a single argument