-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GraphVisitor.ts
50 lines (38 loc) · 1.15 KB
/
GraphVisitor.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
47
48
49
50
import { Edge } from "../Edge";
import { GraphCluster } from "../GraphCluster";
import { GraphNode } from "../GraphNode";
import { VisitedIdTracker } from "./VisitedIdTracker";
export class GraphVisitor {
private visited = new VisitedIdTracker();
constructor(private root: GraphCluster) {}
visitEdges(visit: (edge: Edge) => void) {
const allEdges: Edge[] = [];
const visitedEdges = new VisitedIdTracker();
const addNodeEdges = (node: GraphNode) => {
node.incomingEdges.forEach(edge => {
if (!visitedEdges.isVisitedOrAdd(edge.id)) {
allEdges.push(edge);
}
});
node.outgoingEdges.forEach(edge => {
if (!visitedEdges.isVisitedOrAdd(edge.id)) {
allEdges.push(edge);
}
});
};
this.visitNodesAndClusters(addNodeEdges);
allEdges.map(visit);
}
visitNodesAndClusters(visit: (node: GraphNode) => void) {
const visitNode = (node: GraphNode) => {
if (this.visited.isVisitedOrAdd(node.id)) {
return;
}
visit(node);
if (node instanceof GraphCluster) {
node.nodes.map(visitNode);
}
};
visitNode(this.root);
}
}