0

Consider the following code:

class Node {
  constructor(data = null, parent = null) {
    this.data = data;
    this.parent = parent;
    this.children = [];
  }

  appendChild(data) {
    this.children.push(new Node(data, this.root));
    return this.root;
  }

  toString() {
    return this.data;
  }
}

class NTree {
  constructor(data) {
    this.root = null;
  }

  addRoot(data) {
    this.root = new Node(data);
  }

  find(data) {
    if (this.root.data === data) {
      return this.root;
    }
  }

  appendChild(data) {
    this.root.appendChild(data);
  }

  toString() {
    console.log(this.root);
  }
}

const t = new NTree();
t.addRoot(1);
t.appendChild(2);
t.appendChild(3);
t.appendChild(4);

console.log(t);

The outputs looks as follows:

NTree {
  root: Node { data: 1, parent: null, children: [ [Node], [Node], [Node] ] }
}

How can I convert the above output to this:

NTree {
  root: Node { data: 1, parent: null, children: [ 2, 3, 4 ] }
}
Cody
  • 2,480
  • 5
  • 31
  • 62
  • try `t.push(2)` instead of `t.appendChild(2)` – Layhout May 20 '23 at 02:04
  • @Layhout and how does it help? – Cody May 20 '23 at 02:32
  • 2
    Node only logs 2 levels deep before it starts displaying placeholders. If you want to log more, then you can use one of these options [How can I get the full object in Node.js's console.log(), rather than '\[Object\]'?](https://stackoverflow.com/q/10729276) – Nick Parsons May 20 '23 at 03:19
  • Why do you want to print the root node in a kind of object notation, while you want to print the children as integers. What if those children have children? Secondly, you ask about `toString()`, but that is never called in your code. BTW, the `appendChild` methond on the `Node` class references an unexisting `this.root`. Your parent links are not set up correctly. – trincot May 20 '23 at 06:44

1 Answers1

0

Just do this:

console.log(JSON.stringify(t.root, null, 4));
Cody
  • 2,480
  • 5
  • 31
  • 62