Skip to content

Commit

Permalink
feat: getAllDependents & getAllDependencies
Browse files Browse the repository at this point in the history
  • Loading branch information
adripo authored Oct 23, 2023
1 parent 0c76135 commit 5608d82
Showing 1 changed file with 40 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,22 @@ public T getRoot() {
return rootNode;
}

// Returns all direct and indirect dependents of the node T
public Collection<T> getAllDependents(T node) {
Set<T> allDependents = new HashSet<>();
Set<T> visited = new HashSet<>();
getAllDependentsRecursive(node, allDependents, visited);
return allDependents;
}

// Returns all direct and indirect dependencies of node T
public Collection<T> getAllDependencies(T node) {
Set<T> allDependencies = new HashSet<>();
Set<T> visited = new HashSet<>();
getAllDependenciesRecursive(node, allDependencies, visited);
return allDependencies;
}

public boolean contains(T node) {
return dependencies.containsKey(node);
}
Expand Down Expand Up @@ -192,6 +208,30 @@ private void sortTopologically(T vertex, List<T> visited, List<T> ancestors, Lis
ancestors.remove(vertex);
}

private void getAllDependentsRecursive(T node, Set<T> allDependents, Set<T> visited) {
visited.add(node);
Collection<T> directDependents = getDirectDependents(node);
allDependents.addAll(directDependents);

for (T dependent : directDependents) {
if (!visited.contains(dependent)) {
getAllDependentsRecursive(dependent, allDependents, visited);
}
}
}

private void getAllDependenciesRecursive(T node, Set<T> allDependencies, Set<T> visited) {
visited.add(node);
Collection<T> directDependencies = getDirectDependencies(node);
allDependencies.addAll(directDependencies);

for (T dependency : directDependencies) {
if (!visited.contains(dependency)) {
getAllDependenciesRecursive(dependency, allDependencies, visited);
}
}
}

/**
* Builds a {@code DependencyGraph}.
*
Expand Down

0 comments on commit 5608d82

Please # to comment.