Hyperlinkv0.8.0-beta.28

Graph

Graph.filterMapNodesconsteffect/Graph.ts:1171
<N, E, T extends Kind = "directed">(
  mutable: MutableGraph<N, E, T>,
  f: (data: N) => Option.Option<N>
): void

Filters and optionally transforms nodes in a mutable graph using a predicate function. Nodes that return Option.none are removed along with all their connected edges.

Example (Filtering and mapping nodes)

import { Graph, Option } from "effect"

const graph = Graph.directed<string, number>((mutable) => {
  const a = Graph.addNode(mutable, "active")
  const b = Graph.addNode(mutable, "inactive")
  const c = Graph.addNode(mutable, "active")
  Graph.addEdge(mutable, a, b, 1)
  Graph.addEdge(mutable, b, c, 2)

  // Keep only "active" nodes and transform to uppercase
  Graph.filterMapNodes(
    mutable,
    (data) =>
      data === "active" ? Option.some(data.toUpperCase()) : Option.none()
  )
})

console.log(Graph.nodeCount(graph)) // 2 (only "active" nodes remain)
transforming
Source effect/Graph.ts:117123 lines
export const filterMapNodes = <N, E, T extends Kind = "directed">(
  mutable: MutableGraph<N, E, T>,
  f: (data: N) => Option.Option<N>
): void => {
  const nodesToRemove: Array<NodeIndex> = []

  // First pass: identify nodes to remove and transform data for nodes to keep
  for (const [index, data] of mutable.nodes) {
    const result = f(data)
    if (Option.isSome(result)) {
      // Transform node data
      mutable.nodes.set(index, result.value)
    } else {
      // Mark for removal
      nodesToRemove.push(index)
    }
  }

  // Second pass: remove filtered out nodes and their edges
  for (const nodeIndex of nodesToRemove) {
    removeNode(mutable, nodeIndex)
  }
}