This content originally appeared on Bits and Pieces - Medium and was authored by Aman
JS Interview Question: Create a function that returns curried version of a function
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.
- 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)
- 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 frontend and backend
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 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
- How We Build Micro Frontends
- How we Build a Component Design System
- The Composable Enterprise: A Guide
JavaScript: Create a Function that Returns Curried Version of a Function was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Bits and Pieces - Medium and was authored by Aman
Aman | Sciencx (2022-03-15T10:18:02+00:00) JavaScript: Create a Function that Returns Curried Version of a Function. Retrieved from https://www.scien.cx/2022/03/15/javascript-create-a-function-that-returns-curried-version-of-a-function/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.