I'm trying to pass this deepMap([4,5, [3,4,[2]]], x => x + 5) into this function:
const deepMap = (arr, fn) => {
return arr.reduce((first, second) => first.concat(Array.isArray(second) ? [deepMap(second)] : fn), []);
}
previously it worked like this:
const deepMap = (arr, fn) => {
return arr.reduce((first, second) => first.concat(Array.isArray(second) ? [deepMap(second)] : second + 5), []);
}
but that didn't allow me to use the function in the second parameter. I know it needs to work like the second example, but the only way I can think to change it is like it is in the first example. I have tried numerous variations experimentally but I keep getting an error or the wrong answer.
Array.concatexpects an array -[second + 5]?deepMapfunction the function passed as an argument is namedfn, so you call it likefn(xyz). If you want subsequent recursive calls todeepMapto also be able to call it, you have to pass it on:deepMap(second, fn).