1

我正在尝试在此方法中对 this.isParentEmpty() 进行递归调用,并且一旦访问了所有项目,我就需要停止此递归。也许使用计数器..例如,我将 items.length 设置为 3,那么递归应该只发生在满足长度之前并在此之后中断,以避免无限循环或循环依赖.. 什么可能是停止条件为了这??

isParentEmpty(item, items) {
  const parentSystemRecordId = R.path(['parent', 'id'], item);
  
  if(!parentSystemRecordId || !item.isDependentList) {
    return false;
  }
  
  const parentItem = 
    items.find(({ _id }) => Number(_id) === parentSystemRecordId);
          
  if(this.isParentEmpty(parentItem, items)) {
    return true;
  }
          
  return parentItem && !R.path(['value', 'id'], parentItem);
}
4

1 回答 1

1

你可以在你的函数中传递一个Set标记你访问过的项目。

要检查您是否应该处理一个项目,您可以使用 来检查您的集合visited.has(item)

不确定您的具体示例,但这里有一个更通用的概念证明:

const nodeA = { id: "A", links: [] };
const nodeB = { id: "B", links: [] };
const nodeC = { id: "C", links: [] };
const nodeD = { id: "D", links: [] };

// Create a circular structure
nodeA.links.push(nodeB);
nodeB.links.push(nodeC);
nodeC.links.push(nodeC);
nodeB.links.push(nodeD);
nodeD.links.push(nodeA);

// Write a recursive function that will only visit each node once
const visitOnce = (node, f, visited = new Set(), distance = 0) => {
  // Mark the node as visited
  visited.add(node);
  
  // Execute some logic / side effect
  f(node, distance);
  
  node.links
    // Prevent recursion for nodes that have been visited
    .filter(n => !visited.has(n))
    // Recurse, pass the set along
    .forEach(n => visitOnce(n, f, visited, distance + 1));
}


visitOnce(nodeA, (n, d) => console.log(`${n.id} at distance ${d}`));

于 2021-10-21T08:01:22.037 回答