DEV Community

Cover image for Javascript Currying #1
chandra penugonda
chandra penugonda

Posted on • Edited on

2 1 1 1

Javascript Currying #1

Currying is a useful technique used in JavaScript applications.

Please implement a curry() function, which accepts a function and return a curried one.

Good morning! Here's your coding interview problem for today.

This problem was asked by Google.

Currying is a useful technique used in JavaScript applications.

Please implement a curry() function, which accepts a function and return a curried one.

Example

const multiplyThree = (a, b, c) => {
   return a * b * c;
};

const curriedMultiplyThree = curry(multiplyThree);

console.log(curriedMultiplyThree(1, 3, 5)); // 15
console.log(curriedMultiplyThree(1, 2)(5)); // 10
console.log(curriedMultiplyThree(1)(2)(3)); // 6

Enter fullscreen mode Exit fullscreen mode

Note: The implementation of curry() is not provided and needs to be completed.

Solution

function curry(fn) {
  return function curried(...args) {
    if (fn.length === args.length) {
      return fn.apply(this, args);
    }
    return (...args2) => curried.apply(this, args.concat(args2));
  };
}
Enter fullscreen mode Exit fullscreen mode

Explanation

  • When you call curry() and pass it a function, it returns a new curried() function.
  • The first time you call curried() and pass it some arguments, it checks if the number of arguments matches the required arguments for the original function.
  • If it does match, it calls the original function with those arguments.
  • If it doesn't match, it returns a new function that will accumulate more arguments and call curried() again.
  • This continues until enough arguments have been accumulated to call the original function.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay