Skip to main content
Lookup functions provide fast O(1) access to nodes and edges by ID using transparent internal indexing.

getNode

Get a node by id, or undefined if not found.
export function getNode<N>(
  graph: Graph<N>,
  id: string
): GraphNode<N> | undefined
graph
Graph<N>
required
The graph to search.
id
string
required
ID of the node to retrieve.
node
GraphNode<N> | undefined
The node with the specified ID, or undefined if not found.

Examples

const graph = createGraph({ nodes: [{ id: 'a' }] });
const node = getNode(graph, 'a');
// node.id === 'a'
// node.type === 'node'

getEdge

Get an edge by id, or undefined if not found.
export function getEdge<E>(
  graph: Graph<any, E>,
  id: string
): GraphEdge<E> | undefined
graph
Graph<any, E>
required
The graph to search.
id
string
required
ID of the edge to retrieve.
edge
GraphEdge<E> | undefined
The edge with the specified ID, or undefined if not found.

Examples

const graph = createGraph({
  nodes: [{ id: 'a' }, { id: 'b' }],
  edges: [{ id: 'e1', sourceId: 'a', targetId: 'b' }],
});
const edge = getEdge(graph, 'e1');
// edge.id === 'e1'
// edge.sourceId === 'a'
// edge.targetId === 'b'

hasNode

Check if a node exists in the graph.
export function hasNode(graph: Graph, id: string): boolean
graph
Graph
required
The graph to search.
id
string
required
ID of the node to check.
exists
boolean
true if the node exists, false otherwise.

Examples

const graph = createGraph({ nodes: [{ id: 'a' }] });
hasNode(graph, 'a'); // true

hasEdge

Check if an edge exists in the graph.
export function hasEdge(graph: Graph, id: string): boolean
graph
Graph
required
The graph to search.
id
string
required
ID of the edge to check.
exists
boolean
true if the edge exists, false otherwise.

Examples

const graph = createGraph({
  nodes: [{ id: 'a' }, { id: 'b' }],
  edges: [{ id: 'e1', sourceId: 'a', targetId: 'b' }],
});
hasEdge(graph, 'e1'); // true

Performance

All lookup functions use O(1) hash-based indexing:
  • First access: Index is built automatically (O(n) for nodes + edges)
  • Subsequent accesses: O(1) lookup from WeakMap cache
  • After mutations: Index is invalidated and rebuilt on next access
The indexing is transparent and requires no manual cache management.

Example: Index lifecycle

const graph = createGraph({ nodes: [{ id: 'a' }] });

// First lookup: builds index (O(n))
getNode(graph, 'a'); // → builds WeakMap index

// Second lookup: uses cached index (O(1))
getNode(graph, 'a'); // → instant lookup

// Mutation: invalidates index
addNode(graph, { id: 'b' });

// Next lookup: rebuilds index (O(n))
getNode(graph, 'b'); // → rebuilds index with new node

Build docs developers (and LLMs) love