Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

228
Visualizações
Stop this recursive call once all the items in the items(array) is visited (JavaScript)

I am trying to make a recursion call of this.isParentEmpty() inside this method and I need to stop this recursion once all the items are visited . Maybe using a counter.. Here for example I have items.length as 3 then the recursion should only happen till the time the length is met and break after that in order to avoid infinite loop or circular dependencies.. What could be the stopping condition for this??

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);
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can pass a Set along in your function that marks which items you have visited.

To check whether you should process an item, you can check your set with visited.has(item).

Not sure about your specific example, but here's a more generic proof of concept:

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}`));

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda