Implement a deepMap function
We need to create a deepMap
utility which can return a new result by invoking a callback function against each value of the input recursively. Only JSON serializable values will be passed as input.
Basically, we need to achieve the following:
- If the value is any primitive type, simple invoke the callback with the value.
- If the value is any non-primitive type, recursively go to all depths and invoke the callback to get the result.
We should not mutate the original input.
1. Basic implementation
2. this keyword implementation
In above implementation we simply invoked the callback without considering the “this” keyword for the callback. In this version, every call of the callback but have reference of “this” keyword bound to the original input.
Most of the implementation here remains same, expect how we invoke the callback function. For simpler access to the original input argument, I have also created a inner helper recursion function.
3. Pipe implementation
In this implementation, we have have function values present at any nested level of the object. Each function values must be evaluated and returned on the result.
This technique requires working knowledge of JavaScript closures, so I recommend my Closure Questions for Frontend Interview blog series to get practice with some common closure questions.
We’ll update the above implement of “this” keyword variation, to return a function now instead of result. This returned function then can be further called by a set of arguments which we will pipe through on our object to get the final state.
I’m marking the new changes for easier access;
Further Reading
I strongly encourage you to explore and tackle additional questions in my Recursion Questions for Frontend Interviews blog series.
By doing so, you can enhance your understanding and proficiency with recursion, preparing you to excel in your upcoming frontend interviews.
Wishing you best. Happy Interviewing 🫡.