| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
package com.google.javascript.jscomp.graph; |
| 18 |
|
| 19 |
import com.google.common.base.Predicate; |
| 20 |
import com.google.javascript.jscomp.graph.DiGraph.DiGraphEdge; |
| 21 |
import com.google.javascript.jscomp.graph.DiGraph.DiGraphNode; |
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
public class GraphPruner<N, E> { |
| 37 |
private final DiGraph<N, E> graph; |
| 38 |
|
| 39 |
public GraphPruner(DiGraph<N, E> graph) { |
| 40 |
this.graph = graph; |
| 41 |
} |
| 42 |
|
| 43 |
public LinkedDirectedGraph<N, E> prune(Predicate<N> keep) { |
| 44 |
LinkedDirectedGraph<N, E> workGraph = cloneGraph(graph); |
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
for (DiGraphNode<N, E> node : workGraph.getDirectedGraphNodes()) { |
| 49 |
for (DiGraphEdge<N, E> inEdge : node.getInEdges()) { |
| 50 |
for (DiGraphEdge<N, E> outEdge : node.getOutEdges()) { |
| 51 |
N source = inEdge.getSource().getValue(); |
| 52 |
N dest = outEdge.getDestination().getValue(); |
| 53 |
if (!workGraph.isConnectedInDirection(source, dest)) { |
| 54 |
workGraph.connect(source, outEdge.getValue(), dest); |
| 55 |
} |
| 56 |
} |
| 57 |
} |
| 58 |
} |
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
LinkedDirectedGraph<N, E> resultGraph = |
| 63 |
LinkedDirectedGraph.create(); |
| 64 |
for (DiGraphNode<N, E> node : workGraph.getDirectedGraphNodes()) { |
| 65 |
if (keep.apply(node.getValue())) { |
| 66 |
resultGraph.createNode(node.getValue()); |
| 67 |
|
| 68 |
for (DiGraphEdge<N, E> outEdge : node.getOutEdges()) { |
| 69 |
N source = node.getValue(); |
| 70 |
N dest = outEdge.getDestination().getValue(); |
| 71 |
if (keep.apply(dest)) { |
| 72 |
resultGraph.createNode(dest); |
| 73 |
if (source != dest && |
| 74 |
!resultGraph.isConnectedInDirection(source, dest)) { |
| 75 |
resultGraph.connect(source, outEdge.getValue(), dest); |
| 76 |
} |
| 77 |
} |
| 78 |
} |
| 79 |
} |
| 80 |
} |
| 81 |
|
| 82 |
return resultGraph; |
| 83 |
} |
| 84 |
|
| 85 |
private static <N, E> LinkedDirectedGraph<N, E> cloneGraph( |
| 86 |
DiGraph<N, E> graph) { |
| 87 |
LinkedDirectedGraph<N, E> newGraph = LinkedDirectedGraph.create(); |
| 88 |
for (DiGraphNode<N, E> node : graph.getDirectedGraphNodes()) { |
| 89 |
newGraph.createNode(node.getValue()); |
| 90 |
|
| 91 |
for (DiGraphEdge<N, E> outEdge : node.getOutEdges()) { |
| 92 |
N dest = outEdge.getDestination().getValue(); |
| 93 |
newGraph.createNode(dest); |
| 94 |
newGraph.connect(node.getValue(), outEdge.getValue(), dest); |
| 95 |
} |
| 96 |
} |
| 97 |
|
| 98 |
return newGraph; |
| 99 |
} |
| 100 |
} |