5

JavaScript: Create a Function that Returns Curried Version of a Function

 2 years ago
source link: https://blog.bitsrc.io/common-javascript-interview-question-create-a-function-that-returns-curried-version-of-a-function-192bcac8c55a
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

JavaScript: Create a Function that Returns Curried Version of a Function

JS Interview Question: Create a function that returns curried version of a function

Photo by Michael Dziedzic on Unsplash

Let’s create a function that can take any function as an argument, and return a curried version of that. If you need a review of what currying is, check out this link.

The goal is to create a single method, which allows us to return a curried version of any function below:

Before we come up with a solution, we know that we want to transform our math functions from taking multiple arguments, to now accepting a sequences of functions.

How is this possible? How can we determine whether enough sequence of functions have been provided?

Let’s look at some code:

In our solution, we have to return a function that has two logical outcomes.

  1. If the number of arguments provided have are greater or equal than the number of arguments in our callback function, we can proceed. (Demonstrated in the ‘if’ part of our logic)
  2. If we do not have enough arguments yet, we can return a new function in our sequence of functions. We can do this by recalling our nest curried function but this time with all previous arguments. (Demonstrated in the ‘else’ part of our logic)

And that’s it! Hopefully you can review this from time to time to help refresh your memory, in preparation for any upcoming JavaScript interviews.

Thank you for reading. I hope you have found this useful.

Build composable web applications

Don’t build web monoliths. Use Bit to create and compose decoupled software components — in your favorite frameworks like React or Node. Build scalable and modular web applications with a powerful and enjoyable dev experience.

Bring your team to Bit Cloud to host and collaborate on components together, and greatly speed up, scale, and standardize development as a team. Start with composable frontends like a Design System or Micro Frontends, or explore the composable backend. Give it a try →

Learn More


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK