Hyperlinkv0.8.0-beta.28

Graph

Graph.addNodeconsteffect/Graph.ts:623
<N, E, T extends Kind = "directed">(
  mutable: MutableGraph<N, E, T>,
  data: N
): NodeIndex

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

When to use

Use to allocate a new node in a mutable graph before storing edges or querying it by index.

Details

The returned index is allocated from the graph's next node index. The mutable graph stores the node data and initializes empty incoming and outgoing edge indexes for the new node.

Gotchas

NodeIndex values are identifiers and are not reused after removals.

Example (Adding nodes)

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")
  console.log(nodeA) // NodeIndex with value 0
  console.log(nodeB) // NodeIndex with value 1
})
Source effect/Graph.ts:62318 lines
export const addNode = <N, E, T extends Kind = "directed">(
  mutable: MutableGraph<N, E, T>,
  data: N
): NodeIndex => {
  const nodeIndex = mutable.nextNodeIndex

  // Add node data
  mutable.nodes.set(nodeIndex, data)

  // Initialize empty adjacency lists
  mutable.adjacency.set(nodeIndex, [])
  mutable.reverseAdjacency.set(nodeIndex, [])

  // Update graph allocators
  mutable.nextNodeIndex = mutable.nextNodeIndex + 1

  return nodeIndex
}