Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 12 additions & 19 deletions lib/common/graph.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,32 +106,25 @@ class DirectedGraph {
sourceVertices = [sourceVertices];
}

// Track our descent
const visited = {};
const visited = new Set(sourceVertices);
const queue = [...sourceVertices];

// Initialize the state
sourceVertices.forEach(v => { visited[v] = true; });

// Perform a BFS search of the graph.
let currentVertex;
while (queue.length > 0) {
currentVertex = queue[0];
queue.shift();

const edges = this.adjacencyMap[currentVertex] || [];

edges.forEach(edge => {
if (!visited[edge]) {
visited[edge] = true;
queue.push(edge);
// BFS using an index pointer
for (let i = 0; i < queue.length; i++) {
const edges = this.adjacencyMap[queue[i]];
if (edges) {
for (let j = 0; j < edges.length; j++) {
if (!visited.has(edges[j])) {
visited.add(edges[j]);
queue.push(edges[j]);
}
}
});
}
}

return new DirectedGraph(Object.fromEntries(
Object.entries(this.adjacencyMap)
.filter(([vertex]) => visited[vertex])
.filter(([vertex]) => visited.has(vertex))
));
}

Expand Down
Loading