The goal
I'm trying to create a "deepMapValues" function. It will take a function like...
(v, k) => k == 'hello' ? 'world' : v;
// if the key is 'hello' then return the value 'world' else return the value that already exists there.
And an object like...
{
hello: true,
foo: {
hello: 'bar'
}
}
And return the object..
{
hello: 'world',
foo: {
hello: 'world'
}
}
Using it like this... deepMap(mapFunction)(inputObject)
My current function
I wrote this small function using lodash...
const mapValuesWithKey = _.mapValues.convert({ 'cap': false });
// this is because I want both the value and key passed into the map function
deepMap = fn => mapValuesWithKey(
_.cond([
[_.isArray, _.map(deepMap(fn))],
[_.isPlainObject, deepMap(fn)],
[_.T, fn],
])
);
When I run it I instantly get the crash...
RangeError: Maximum call stack size exceeded
Which could be expected as the function is recursive and so if not done correctly it will infinitely recurse.
However, I changed it to this (just for testing)...
deepMap = fn => mapValuesWithKey(
_.cond([
[_.T, fn],
])
);
And it worked (which again is expected).
But when I changed it to this...
deepMap = fn => mapValuesWithKey(
_.cond([
[_.T, fn],
[_.F, deepMap(fn)],
])
);
It crashed again with the same error. Even though the recursion will NEVER happen in the above code it was still exceeding the call stack size.
Using the lodash code from Github I suspected it might be evaluating all the pairs in _.cond before running the code so I wrote my own version of cond.
const myCond = pairs => {
return (...args) => {
for (const pair of pairs) {
if (pair[0](args)) {
return pair[1](args)
}
}
}
};
But this also still crashed.
I'm not sure what I'm doing wrong here now as it seems to be recursing even when it should be impossible for it to recurse?
What am I doing wrong?
Thanks
Rubber Duck EDIT
I think it might be because the function is evaluating with the fn parameter and then that creates the object in the cond pair that recurses with fn which does the same again and again and again...
Investigating.
Further question
If the above is true... how can I stop the error but still pass the fn through the recursion?