Search code examples
javascriptloopsdynamic-datajavascript-objects

Dynamic Javascript Hierarchy Loop


The following code builds a hierarchy of nodes with 3 fixed levels (3 nodes):

     function createNode(name) {
     return({name: name, children: []});
     }
     function addChild(node, child) {
     node.children.push(child);

      return node;
      }
      var tree = createNode("");
      var subChild = createNode("");
      addChild(subChild, createNode("A31"));

      addChild(tree, subChild);

How do I alter this code so that the number of levels created in the hierarchy is not fixed. How do I make the creation of nodes dynamic, in that the number of nodes are not known and will vary depending on the some data passed. How is done so that the hierarchy size can be built and defined dynamically. Can loops be applied in the above code to achieve this?


Solution

  • /**
     * Just parses a string in a specific format
     * @return object
     * {
     *    name, // Name of the node
     *    childens // Array of child nodes IN STRING REPRESENTATION
     * }
     */
    function parseNodeStr(str) {
      // @to-do
    }
    
    function createNode(defStr) {
      var node = false;,
          nodeParsed = parseNodeStr(defStr);
    
      if (nodeParsed) {
        node = {};
        node.name = nodeParsed.name;
        node.childrens = [];
        for (child in nodeParsed.childs) {
           addChild(node, createNode(child);
        }
      }
    
      return node;
    }
    
    function addChild(node, child) {
      if (child) {
        node.childrens.push(child);
      }
    
      return node;
    }
    
    var node = createNode("(node1,[(node2,[(n3),(n4)])])");
    

    I hope it helps you.