Recursion with higher order functions
The code can equivalently (and, imho, cleaner) be written with a normal loop and a conditional instead of filter
and forEach
:
function makeTree(categories, parent) {
let node = {};
for (const c of categories)
if (c.parent == parent)
node[c.id] = makeTree(categories, c.id);
return node;
}
Now it's just an ordinary recursive function, nothing higher-order left.
Also, regarding the forEach
callback specifically, that uses a totally unnecessary grouping parenthesis in the shorthand arrow function syntax instead of properly writing it with a block body (since nothing needs to be returned from a forEach
callback):
.forEach(c => {
node[c.id] = makeTree(categories, c.id);
});