Hyperlinkv0.8.0-beta.28

Graph

Graph.addEdgeconsteffect/Graph.ts:1411
<N, E, T extends Kind = "directed">(
  mutable: MutableGraph<N, E, T>,
  source: NodeIndex,
  target: NodeIndex,
  data: E
): EdgeIndex

Adds a new edge to a mutable graph and returns its index.

When to use

Use to connect two existing nodes in a mutable graph while storing edge data and receiving the new edge identifier.

Details

Creates an Edge with the source, target, and data at the next edge index, updates adjacency indexes, and increments the graph's next edge index. Undirected graphs register the same edge for both endpoints.

Gotchas

The source and target nodes must already exist in the mutable graph; missing endpoints throw a GraphError.

Example (Adding edges)

import { Graph } from "effect"

const result = Graph.mutate(Graph.directed<string, number>(), (mutable) => {
  const nodeA = Graph.addNode(mutable, "Node A")
  const nodeB = Graph.addNode(mutable, "Node B")
  const edge = Graph.addEdge(mutable, nodeA, nodeB, 42)
  console.log(edge) // EdgeIndex with value 0
})
Source effect/Graph.ts:141153 lines
export const addEdge = <N, E, T extends Kind = "directed">(
  mutable: MutableGraph<N, E, T>,
  source: NodeIndex,
  target: NodeIndex,
  data: E
): EdgeIndex => {
  // Validate that both nodes exist
  if (!mutable.nodes.has(source)) {
    throw missingNode(source)
  }
  if (!mutable.nodes.has(target)) {
    throw missingNode(target)
  }

  const edgeIndex = mutable.nextEdgeIndex

  // Create edge data
  const edgeData = new Edge({ source, target, data })
  mutable.edges.set(edgeIndex, edgeData)

  // Update adjacency lists
  const sourceAdjacency = mutable.adjacency.get(source)
  if (sourceAdjacency !== undefined) {
    sourceAdjacency.push(edgeIndex)
  }

  const targetReverseAdjacency = mutable.reverseAdjacency.get(target)
  if (targetReverseAdjacency !== undefined) {
    targetReverseAdjacency.push(edgeIndex)
  }

  // For undirected graphs, add reverse connections
  if (mutable.type === "undirected") {
    const targetAdjacency = mutable.adjacency.get(target)
    if (targetAdjacency !== undefined) {
      targetAdjacency.push(edgeIndex)
    }

    const sourceReverseAdjacency = mutable.reverseAdjacency.get(source)
    if (sourceReverseAdjacency !== undefined) {
      sourceReverseAdjacency.push(edgeIndex)
    }
  }

  // Update allocators
  mutable.nextEdgeIndex = mutable.nextEdgeIndex + 1

  // Only invalidate cycle flag if the graph was acyclic
  // Adding edges cannot remove cycles from cyclic graphs
  invalidateCycleFlagOnAddition(mutable)

  return edgeIndex
}