-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathtree.ts
46 lines (40 loc) · 1.16 KB
/
tree.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
* Generated by Github Copilot.
*/
export default class Tree<T> {
data: T;
parent: Tree<T> | null = null;
readonly children: Tree<T>[] = [];
constructor(data: T, parent: Tree<T> | null = null) {
this.data = data;
this.parent = parent;
}
appendChild(child: T | Tree<T>): Tree<T> {
const tree = child instanceof Tree ? child : new Tree<T>(child, this);
this.children.push(tree);
return tree;
}
removeChild(tree: Tree<T>): void {
const index = this.children.indexOf(tree);
if (index > -1)
this.children.splice(index, 1);
}
traverse(callback: (data: T) => void): void {
callback(this.data);
this.children.forEach((child) => child.traverse(callback));
}
clear(): void {
// this.children.forEach((child) => child.clear());
this.children.length = 0;
}
find(data: T): Tree<T> | null {
if (this.data === data)
return this;
for (const child of this.children) {
const result = child.find(data);
if (result)
return result;
}
return null;
}
}