0

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?

1 Answer 1

1
/**
 * 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.

Sign up to request clarification or add additional context in comments.

4 Comments

Ok, but I need the generated hierarchy and all its data to be represented in var treeData. How can that be done?
yes :) var treeData = createNode("(node1,[(node2,[(n3),(n4)])])");
Ok, I guess that would mean replacing var node (last line) with var treeData? Also, I am having trouble understanding what to do for :function parseNodeStr(str) { // @to-do } I am sorry, but I am very novice to this level of code.
for that function, i just say, what it should do, and the implementation should be done (to do)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.