(edges: Edge[], sourceId: string, targetId: string)
| 27 | * @returns true if adding this edge would create a cycle |
| 28 | */ |
| 29 | export function wouldCreateCycle(edges: Edge[], sourceId: string, targetId: string): boolean { |
| 30 | if (sourceId === targetId) { |
| 31 | return true |
| 32 | } |
| 33 | |
| 34 | const adjacencyList = new Map<string, string[]>() |
| 35 | for (const edge of edges) { |
| 36 | if (!adjacencyList.has(edge.source)) { |
| 37 | adjacencyList.set(edge.source, []) |
| 38 | } |
| 39 | adjacencyList.get(edge.source)!.push(edge.target) |
| 40 | } |
| 41 | |
| 42 | const visited = new Set<string>() |
| 43 | |
| 44 | function canReachSource(currentNode: string): boolean { |
| 45 | if (currentNode === sourceId) { |
| 46 | return true |
| 47 | } |
| 48 | |
| 49 | if (visited.has(currentNode)) { |
| 50 | return false |
| 51 | } |
| 52 | |
| 53 | visited.add(currentNode) |
| 54 | |
| 55 | const neighbors = adjacencyList.get(currentNode) || [] |
| 56 | for (const neighbor of neighbors) { |
| 57 | if (canReachSource(neighbor)) { |
| 58 | return true |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | return false |
| 63 | } |
| 64 | |
| 65 | return canReachSource(targetId) |
| 66 | } |
| 67 | |
| 68 | /** |
| 69 | * Convert UI loop block to executor Loop format |
no test coverage detected