Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

229
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!