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
ID of the node to retrieve.
The node with the specified ID, or undefined if not found.Show GraphNode properties
Entity type discriminator (always 'node').
ID of the parent node, or null for top-level nodes.
ID of the initial child node (for compound states).
Display label (empty string if not provided).
Custom data attached to the node.
style
Record<string, string | number>
Custom style properties.
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
ID of the edge to retrieve.
The edge with the specified ID, or undefined if not found.Show GraphEdge properties
Entity type discriminator (always 'edge').
Display label (empty string if not provided).
Custom data attached to the edge.
style
Record<string, string | number>
Custom style properties.
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
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
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
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