Solving the problem of endless looping in JavaScript tree structures

i have been trying to create a tree structure in JavaScript. However, when I use the add_child function to add a child to an item in the elements array, it adds the child to all items in the elements array and their children, creating an infinite loop.

I am unsure why this is happening.

let divBase = {
  Name: "",
  Type: "div",
  children: [],
  open: false
};

let elements = [];

let elementCounter = 0;

function add_child(parentName, childName) {
  let parent = findItem(parentName)
  let child = removeItem(childName)

  console.log(parent)
  console.log(child)

  if (child != null) {
    parent.children.push(child)
    console.log(parent)
    console.log(child)
    return true
  }
  return false
}

// more functions and code...

if i print the elements array it is like this

(5) [{…}, {…}, {…}, {…}, {…}]

0 : {Name: 'Div 0', Type: 'div', children: Array(1), backgroundColor: '#2ecc71', width: 200, …}
1 : {Name: 'Div 1', Type: 'div', children: Array(1), backgroundColor: '#2ecc71', width: 200, …} 
2 : {Name: 'Div 2', Type: 'div', children:
> Array(1), backgroundColor: '#2ecc71', width: 200, …}
3 : {Name: 'Div 3', Type: 'div', children: Array(1), backgroundColor: '#2ecc71',
> width: 200, …}
4 : {Name: 'Div 5', Type: 'div', children: Array(1), backgroundColor: '#2ecc71', width: 200, …} length :  5

thanks

Answer №1

When working with recursive functions, it is crucial to ensure that they terminate at some point. For instance, in the findItem() function provided, the search continues even after finding the desired node.

An improved version of the code ensures termination upon finding the required value:

function findItem(item) {

  function search(children) {
    for (let i = 0; i < children.length; i++) {
      const child = children[i];
      if (child.Name === item) {
        return child; // <-------- return when found
      }
      if (child.children.length !== 0) {
        const inChild = search(child.children);
        if (inChild) return inChild // <-------- return result if found further down
      }
    }
    return null // <------ continue searching
  }

  return search(elements);
}

The issue of continuous searching without terminating has also been addressed in your findAndRemove() function.

I hope this clarification helps!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The width of sibling divs in IE7 does not match their sibling's width

Currently facing a challenge with resolving an IE7 problem. My goal is to ensure that my sibling div has the same width as its counterparts. The initial sibling serves as the header, whereas the subsequent siblings have specific dimensions. Any advice woul ...

Managing a new browser window using Selenium

I am attempting to automate a download process on a webpage using selenium. Upon clicking a button, a blank popup window appears. After approximately 60 seconds, a link appears within the popup that I want to click on. The code snippet below outlines my ap ...

Utilize Moment to round a date either up or down

I am using Moment to compare two datetime values. Specifically, I am utilizing Moment.isSameOrBefore function. However, my two date values are slightly different due to milliseconds. I want these two values to be considered the same: var date1 = ' ...

Connect a nearby dependency to your project if it has the same name as an npm repository

What is the best way to npm link a local dependency that has the same name as a project in the npm registry, like https://registry.npmjs.org/react-financial-charts? Here is an example: cd ~/projects/react-financial-charts // Step 1: Navigate to the packa ...

The ancient oracle of Delphi and the modern login portal of Microsoft

I need to login to a site that utilizes . To streamline the process for end-users, I want to store credentials in an .ini file and inject them into a two-stage JavaScript online prompt. Is there a way to have Delphi run a program with a browser that auto ...

What is the process for setting up both an open and closed status for my accordion?

After browsing through multiple threads on accordions, none seem to match my current structure which I believed was effective. In an attempt to learn and build elements from scratch, I created the following accordion with some help from Google and experi ...

In the React js and emotion framework, fonts are only loaded in production mode after the page has been re

I have set up emotion's Global component to globally apply a font to my app: export const GlobalStyle: FC<{}> = () => ( <Global styles={css` @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@100;300;400;50 ...

Stylish border radius for Bootstrap progress bars

Here is a snippet of code that I am struggling with: .progress-bar{ border-top-right-radius: 40px !important; border-bottom-right-radius: 40px !important; -webkit-box-shadow: none !important; -moz-box-shadow: none !important; box-sha ...

Tips for customizing the color of mat-select placeholder text?

I've been attempting to modify the color of a mat-select placeholder. It functions properly when using 'background-color' but not when using 'color'. Below is my CSS code: /deep/ .mat-select-placeholder { color: red; } .mat-s ...

How do I access the content of a webpage once it has been generated using a template engine?

Currently, I am engaging in screen scraping for a website that heavily relies on JavaScript. The site utilizes a client-side templating engine to display all of its content. Initially, I attempted to use jQuery, which proved successful in the console but n ...

Connect ngx-time picker to form input in Angular

Currently, I have successfully implemented Angular material date pickers in my project, however, I am facing a challenge with integrating time pickers as it is not natively supported by Angular Material for version 8. To address this issue, I am utilizing ...

The issue with $.parseJSON when encountering double quotes

Could someone please clarify why a JSON string with double quotes can disrupt the functionality of $.parseJSON? This example works: [{"type":"message","content":{"user":"tomasa", "time":"1321722536", "text":"asdasdasd"}}] And so does this one: [{"type" ...

Bordering the isotopes

Currently, I am utilizing a plugin that involves the isotope filter library. By setting the width to 33.33%, my list elements are organized into 3 columns. I am trying to specify the middle column to have side borders. However, whenever I click on the filt ...

What are the best methods for adjusting the size of a game's

I create games using HTML5/CSS/JS, but I am struggling to figure out how to make them scale to different screen resolutions. It seems like a simple task, but I can't seem to grasp it. SOLVED var RATIO = 480 / 800; // Initial ratio. function resize() ...

Implementing Browser Back or Back button in AngularJS

Currently, I am developing an application that utilizes route methods to navigate between webpages for different modules. Essentially, it is a single page application with route methods responsible for loading the HTML content in the body section. The iss ...

What is the proper way to include onMouseOver and onMouseEnter events in a reactjs project

Seeking assistance with implementing the onMouseOver event in React, but encountering issues. I have followed the correct procedures for using, calling, and setting State. Please review my code and provide guidance. import React from 'react'; c ...

Creating a Dynamic Layout with Varying Items in an Array Using PHP

Suppose I provide you with an array of objects, where x represents the number of objects. How would you achieve the following using a grid system (bootstrap, foundation, etc.)? Loop over the array and generate something similar to: I have managed to crea ...

Dropdown box not displaying any choices

I developed a basic reusable component in the following way: Typescript (TS) import {Component, Input, OnInit} from '@angular/core'; import {FormControl} from '@angular/forms'; @Component({ selector: 'app-select', templa ...

Choose a single dynamic image from a collection of multiple images

In the process of developing a Shopping cart website, I encountered an issue regarding allowing users to upload multiple images of a single product. Using jQuery, I successfully cloned the file input section to enable uploading additional images of the sam ...

Transmitting special symbols through Socket.io

I've been working on a small project based on Socketio 0.9 and everything is running smoothly, except for a minor problem with special characters. In the web client, I am creating a dynamic JSON object using JavaScript that is then emitted to the ser ...