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

How can we use the Selenium JavascriptExecutor in Java to return an Object from JavaScript?

I've encountered an issue while running a JavaScript file using Java with Selenium in my application. When I execute the JavaScript file with JavascriptExecutor after logging in, I'm only getting a null return instead of a valid one. Below is a ...

Receiving server data with socket.io in Node.js

I have set up a Node.js server to send data to an HTML client using socket.io: var spawn = require('child_process').spawn; var child = spawn('node', ['file.js']); child.stdin.write("Hello there!"); child.stdout.on(&apo ...

Tips for managing @ManyToMany relationships in TypeORM

In this scenario, there are two distinct entities known as Article and Classification, linked together by a relationship of @ManyToMany. The main inquiry here is: How can one persist this relationship effectively? The provided code snippets showcase the ...

Understanding the process of accessing data within the beforeRouteLeave component guard in Vue

Having trouble accessing data within beforeRouteLeave as everything appears to be undefined Check out the code snippet below: <template> ... </template> <style lang="scss"> ... </style> <script> export default { ...

An unexpected error has occurred within React Native, indicating that an object is

It's baffling why I keep receiving the error message: "undefined is not an object (evaluating '_this.props.navigation.navigate')" I am fairly new to react and have tried every possible solution but still cannot resolve this error. Belo ...

Showing every piece of information line by line while uploading an AJAX CSV file

I have successfully parsed a CSV file using Papaparse, Jquery AJAX, and PHP. Now, I want to display the data line by line while the CSV file is being uploaded. Here is a snippet of my code: var xhr_file = null; $('#fileVariants').change(functio ...

Combining Two Tables Using jQuery

I am currently attempting to combine two tables into one using jQuery in the following manner: var table = document.createElement("table"); table.id = "mergedTable"; $("#mergedTable > tbody:last") .append($("#csvInfoTable2 > tbody").html()) ...

What is the best way to transfer a request parameter from a URL to a function that generates an object with matching name in JavaScript?

I need to figure out how to pass a request parameter from an express router request to a function that should return an object with the same name. The issue I'm facing is that the function is returning the parameter name instead of the object. Upon c ...

Executing the onSuccess callback in Ajax without any ability to manipulate the ajax requests

My dilemma lies in needing to execute a JavaScript function upon the successful completion of an AJAX call. Unfortunately, I am unable to directly manage the AJAX calls as they are handled by the DNN5 framework. Is there a way for me to trigger my functio ...

How can I adjust the timeout or enhance my code for Excel Online's ExcelScript error regarding the Range getColumn function timing out?

I am struggling with a code that is supposed to scan through the "hello" sheet and remove any columns where the top cell contains the letter B: function main(workbook: ExcelScript.Workbook) { let ws = workbook.getWorksheet("hello"); let usedrange = ws ...

The JQuery category filtering feature malfunctions when a category consists of more than two words

Utilizing Jquery, I have implemented a feature that displays project categories and allows users to filter projects based on the selected category. To view the code pen for this implementation, please click here: https://codepen.io/saintasia/pen/dzqZov H ...

What is the best way to choose a key from a discriminated union type?

I have a discriminated union with different types type MyDUnion = { type: "anonymous"; name: string } | { type: "google"; idToken: string }; I am trying to directly access the 'name' key from the discriminator union, like thi ...

The jQuery tooltip fails to function properly after the AJAX content is loaded

I have been using a tooltip script that can be found at: This is the script I am using, with a few modifications: $(document).ready(function() { $("body").on("mouseover", ".tip_trigger", function(){ tip = $(this).find('.tip&apos ...

Tips for creating a 360 x 235 degree FOV image using three.js

My camera captures round images with a 235-degree field of view, like this one: https://i.sstatic.net/qNfrX.jpg I am familiar with threejs and have successfully rendered 360x360 images as equirectangular projections. However, I want to use threejs to rend ...

It is advised not to use arrow functions to assign data when fetching API data with axios in Vue.js 2

Trying to retrieve data from a URL using Axios in my Vue app is resulting in the error message: Error: Arrow function should not return assignment Complete error message: Error: Arrow function should not return assignment (no-return-assign) at src\co ...

Authorization based on user roles in Node.js or Express.js

Are there any modules available for implementing role-based authorization in node.js or Express js? For example, having roles such as Super Admin, Admin, Editor, and User? ...

How can I use jQuery to switch the positions of two <div> elements in HTML based on the selection of a dropdown value?

I need to switch the display positions of two <div> containers based on a dropdown value change. Can this be accomplished using jQuery? Here are the two div containers whose display positions need to be interchanged: <div id="first"><p> ...

Retrieve information from a website and transfer it to a Google spreadsheet

Despite the wealth of information on this topic, I have yet to find a solution that works for me. My goal is to transfer variables obtained from another website to Google Spreadsheet. These are the variables: var a = parseInt($('table.thinline:eq(4) ...

Error: The JavaScript SRC cheat is malfunctioning

Having an issue with the code below. The 'dummy1' and 'dummy2' variables are not loading their content as expected on the page. Any suggestions? <html> <head> <title>JavaScript On-line Test</title> <script LA ...

I am having trouble setting an object in the state using React hooks

When assigning an initial value to a state as null, the setState method does not hold the value when assigned. Calling an API in useState returns an object which cannot be directly put into setState. const [userProfile, setProfile] = useState(null); cons ...