Home > Net >  How to dynamically create a nested tree with depth 10 in JavaScript using a loop
How to dynamically create a nested tree with depth 10 in JavaScript using a loop

Time:07-10

I have a general tree class with: myTree = new Tree(string), appendChildNode(node), createChildNode(string), myTree.print() functions and myTree.name, myTree.children, etc attributes.

I know, I can create a tree depth (10) by hand like so:

// declare new tree
myTree = new Tree('Diagrams')
// adding nodes by hand here    
myTree.createChildNode('A1').createChildNode('A2').createChildNode('A3').createChildNode('A4').createChildNode('A5').createChildNode('A6').createChildNode('A7').createChildNode('A8').createChildNode('A9').createChildNode('A10')
myTree.print()

How would I do that programmatically using a for loop? Expected result depth 10:

Diagrams
 A1
  A2
   A3
    A4
     A5
      A6
       A7
        A8
         A9
          A10

Sorry, if this is a question that was answered before, I just cannot come up with a proper query to search for a solution to this. I think I am missing a syntax in JS for doing that. Info: I took the following general tree implementation: https://github.com/beforesemicolon/tutorials-files/blob/master/tree-generic.js

CodePudding user response:

let tree = new Tree("Diagrams"); // create the tree
let node = tree; // we need this variable so we can assign the current node to it in the loop

for(let i = 0; i < 10; i  ) {
  let name = "A"   (i   1); // the name of the current node
  node = node.createChildNode(name); // create the node with the given name and assign the newly created node so we can create the sub node in the next iteration
}

not tested

CodePudding user response:

Just store previous child in a variable and append new node to it:

// declare new tree
myTree = new Tree('Diagrams')
let child = myTree;
for(let i = 1; i < 11; i  )
{
  child = child.createChildNode('A'   i);
}

myTree.print();

CodePudding user response:

Just loop, adding child to a node, and updating node to be the child and so on. Tested :-)

var myTree = new Tree('Diagrams')
var node = myTree;
var children = 'A1,A2,A3,A4,A5,A6,A7,A8,A9,A10'.split(",");
children.forEach(function(child) {
  node = node.createChildNode(child)
})
myTree.print()

function Tree(tree_name) {
  var children = [];
  var name = tree_name
  this.createChildNode = function(child_name) {
    var child = new Tree(child_name);
    children.push(child)
    return child;
  }
  this.print = function(level) {
    level = level || 0;
    var space = ' '.repeat(level)
    console.log(space   name)
    children.forEach(function(child) {
      child.print(level   1);
    })
  }
}

  • Related