Implement a curry function
Currying is a technique using which we can convert function that takes multiple arguments into a sequence of functions that take a single/multiple argument. It is a common technique used in functional programming languages.
We are suppose to implement a higher order curry function that takes a function as argument and returns a curried version of the function. We can invoke the curries function until the arguments requirements are met after which it returns the result.
1. Basic implementation
We consider that the original function which needs to be curried takes only fixed number of arguments.
2. Sporadic arguments implementation
As in previous case, we curried a function, where we knew the total number of arguments, we were able to terminate and execute the final function once the expectation was met.
If we consider a function that takes sporadic arguments, like a sum function defined as:
In this function we can pass any number of arguments, so curry implementation used above will not work. We need to create a new implementation such that function with sporadic input can also be curried.
But before doing that, we need to revisit the fundamentals of valueOf
to leverage value conversion.
Applying the same principle of valueOf
we can have our sporadic input currying implementation as follows:
We can also implement the same using the Symbol.toPrimitive method as well.
Further Reading
I strongly encourage you to explore and tackle additional questions in my Closure Questions for Frontend Interviews blog series.
By doing so, you can enhance your understanding and proficiency with closures, preparing you to excel in your upcoming frontend interviews.
Wishing you best. Happy Interviewing 🫡.