具有高阶函数的递归

Emh*_*vek 7 javascript recursion ecmascript-6

我想了解以下示例,因此对我来说很清楚。不幸的是,我的头挂在了线上:.forEach(c =>(node [c.id] = makeTree(categories,c.id)))。有人可以给我提示吗?

let categories = [
  { id: 'animals', parent: null },
  { id: 'mammals', parent: 'animals' },
  { id: 'cats', parent: 'mammals' },
  { id: 'dogs', parent: 'mammals' },
  { id: 'chihuahua', parent: 'dogs' },
  { id: 'labrador', parent: 'dogs' },
  { id: 'persian', parent: 'cats' },
  { id: 'siamese', parent: 'cats' }
];

let makeTree = (categories, parent) => {
  let node = {};
  categories
    .filter(c => c.parent == parent)
    .forEach(c => (node[c.id] = makeTree(categories, c.id)));
  return node;
};

console.log(makeTree(categories, null));

expected:

{
  animals: {
    mammals: {
      dogs: {
        chihuahua: null
        labrador: null
      },
      cats: {
        persian: null
        siamese: null
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

Ber*_*rgi 3

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;
}
Run Code Online (Sandbox Code Playgroud)

现在它只是一个普通的递归函数,没有什么高阶的了。

另外,具体而言,对于回调,它在速记箭头函数语法forEach中使用了完全不必要的分组括号,而不是使用块体正确编写它(因为不需要从回调返回任何内容):forEach

.forEach(c => {
  node[c.id] = makeTree(categories, c.id);
});
Run Code Online (Sandbox Code Playgroud)