Common JavaScript 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?
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)