The objective
I have set out to develop a unique "deepMapValues" function. This function is designed to take a specified function and an object, apply the function to each value in the object deeply, and return the modified object accordingly.
(v, k) => k == 'hello' ? 'world' : v;
// If key is 'hello', replace its value with 'world'; otherwise, retain the original value.
For instance, given the following object...
{
hello: true,
foo: {
hello: 'bar'
}
}
The function should transform it into...
{
hello: 'world',
foo: {
hello: 'world'
}
}
This transformation can be achieved by utilizing the function as follows:
deepMap(mapFunction)(inputObject)
The existing function
To implement this functionality, I initially created a small function using lodash library that leverages mapValuesWithKey method.
const mapValuesWithKey = _.mapValues.convert({ 'cap': false });
deepMap = fn => mapValuesWithKey(
_.cond([
[_.isArray, _.map(deepMap(fn))],
[_.isPlainObject, deepMap(fn)],
[_.T, fn],
])
);
Upon executing this function, I encountered a crash with the error message:
RangeError: Maximum call stack size exceeded
Although expected due to recursive nature, simplifying the function resolved the issue temporarily for testing purposes.
Nevertheless, reintroducing recursion within the code led to the same crashing scenario despite no actual recursion occurring.
To address this recurring problem, I attempted to recreate my own version of the cond function from lodash called myCond. However, even this alternative solution failed to prevent the crash.
At this point, I am uncertain about the root cause of the issue and seek guidance on rectifying the situation while maintaining the passage of the fn parameter through the recursion loop.
Rubber Duck EDIT
A likely explanation for the persistent error could be the continuous evaluation and generation of objects within the cond pair, leading to an endless cycle of recursions involving the fn parameter.
Further inquiry
If the above assumption holds true, what measures can be taken to mitigate the error without disrupting the flow of fn during recursion?