From 8d5f3145e9525fee4a41050c5da9320a0c1c339e Mon Sep 17 00:00:00 2001 From: muhammed-abdulkadir Date: Mon, 8 Jun 2026 13:31:29 +0100 Subject: [PATCH] perf(graph): optimize BFS in findConnectedGraph Signed-off-by: muhammed-abdulkadir --- lib/common/graph.js | 31 ++++++++++++------------------- 1 file changed, 12 insertions(+), 19 deletions(-) diff --git a/lib/common/graph.js b/lib/common/graph.js index e3ea787..2f7284a 100644 --- a/lib/common/graph.js +++ b/lib/common/graph.js @@ -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)) )); }