Skip to content

Instantly share code, notes, and snippets.

@madeindjs
Last active September 2, 2019 15:40
Show Gist options
  • Save madeindjs/296870bcd39c668d9600754f796b37d5 to your computer and use it in GitHub Desktop.
Save madeindjs/296870bcd39c668d9600754f796b37d5 to your computer and use it in GitHub Desktop.
import assert = require("assert");
interface ISchemaTree {
id: string;
childs: ISchemaTree[];
}
class Tree {
public nodes: TreeNode[] = [];
public constructor(schema: ISchemaTree, rootId?: string, rootTree?: Tree) {
if (!rootTree) {
rootTree = this;
}
this.nodes.push(new TreeNode(schema.id, rootId, rootTree))
for (const subSchema of schema.childs) {
const subTree = new Tree(subSchema, schema.id, rootTree);
this.nodes = this.nodes.concat(subTree.nodes);
}
}
public find(id: string): TreeNode {
return this.nodes.find(n => n.id == id);
}
}
class TreeNode {
public constructor(public readonly id: string, public readonly parentId: string, private readonly tree: Tree) { }
get parentNode(): TreeNode {
return this.tree.find(this.parentId);
}
}
const myTree = new Tree({
id: 'A',
childs: [
{
id: 'A1',
childs: [
{
id: 'A1A',
childs: []
},
{
id: 'A1B',
childs: []
}
]
},
{
id: 'A2',
childs: []
}
]
});
assert.equal(myTree.find('A1A').parentNode.id, 'A1');
assert.equal(myTree.find('A2').parentNode.id, 'A');
assert.equal(myTree.find('A').parentNode, undefined);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment