nary tree structure in javascript

To create a n-ary tree structure in JavaScript, we can define a Node class with an array of child nodes:

index.tsx
class Node {
  constructor(value) {
    this.value = value;
    this.children = [];
  }
}
90 chars
7 lines

We can then use the Node class to create the root node of the tree:

index.tsx
const tree = new Node('root');
31 chars
2 lines

To add child nodes to the Node instance, we can define a method such as:

index.tsx
addChild(value) {
  const node = new Node(value);
  this.children.push(node);
  return node;
}
95 chars
6 lines

We can then traverse the tree using a variety of algorithms such as depth-first search or breadth-first search. Here is an example of a depth-first search traversal function:

index.tsx
function traverseDF(node, visitFn) {
  visitFn(node);
  node.children.forEach(child => {
    traverseDF(child, visitFn);
  });
}
129 chars
7 lines

This function takes a Node instance and a visitFn function as arguments. The visitFn function is called on each node during the traversal, allowing us to perform some operation on the node.

To use the traversal function, we can call it on the root node of the tree and pass in a function to log the value of each node:

index.tsx
traverseDF(tree, node => console.log(node.value));
51 chars
2 lines

gistlibby LogSnag