export class Node {
constructor(data, children = []) {
console.assert(Array.isArray(children) && children.every((child) => child instanceof Node), children);
this._data = data;
this._parent = null;
this._children = children;
for (let child of this._children)
child._parent = this;
}
// Static
static createTree(tree) {
console.assert(typeof tree === "object", tree);
console.assert(!tree.children || Array.isArray(tree.children), tree);
let {children, ...data} = tree;
return new Node(data, (children || []).map(Node.createTree));
}
// Public
get data() { return this._data; }
get parent() { return this._parent; }
get children() { return this._children; }
flatten() {
return [this, ...this._children.flatMap((child) => child.flatten())];
}
}