@sha1n/dagraph
Version:
Directed acyclic graph utility in TypeScript
79 lines (78 loc) • 2.8 kB
TypeScript
interface Identifiable {
readonly id: string;
}
/**
* Represents the state of the traversal at the current node.
*/
interface TraversalState<T> {
/** The parent node from which the current node was reached. Null for root nodes. */
readonly parent: T | null;
/** The depth of the current node in the traversal (0 for roots). */
readonly depth: number;
/** The index of the current node among its siblings (children of the same parent). */
readonly index: number;
/** The total number of siblings (children of the same parent). */
readonly total: number;
}
/**
* A visitor function called for each node during traversal.
*
* @param node The current node data.
* @param state The state of the traversal at the current node.
* @param context The context object passed to traverse.
*/
type DAGVisitor<T, C> = (node: T, state: TraversalState<T>, context: C) => void;
declare class DAGraph<T extends Identifiable> {
private readonly nodesById;
/**
* Adds the specified identifiable node to the graph.
*/
addNode(data: T): DAGraph<T>;
/**
* @returns the data node identified by the specified id if found, else returns undefined.
*/
getNode(id: string): T | undefined;
/**
* Adds an edge pointing from 'from' to 'to'.
*/
addEdge(from: T, to: T): DAGraph<T>;
/**
* Returns a generator that returns all the nodes in topological order.
* Implements a depth-first-search algorithm.
*/
topologicalSort(): Iterable<T>;
/**
* A generator that returns the traverse roots of this graph.
*/
roots(): Iterable<T>;
/**
* A generator that returns all the nodes in the this graph.
*/
nodes(): Iterable<T>;
/**
* Returns a graph with the same edges pointing in the opposite direction.
*
* @returns a DAGraph
*/
reverse(): DAGraph<T>;
/**
* Traverses the graph in depth-first order and calls the visitor function for each node.
* Siblings (nodes sharing the same parent) are visited in the order they were added`.
*
* Note: This traversal behaves like a tree expansion. If a node is reachable via multiple paths
* (e.g., a "diamond" structure), it will be visited multiple times—once for each path reaching it.
*
*
*
* @param visitor the visitor function to call for each node.
* @param context the context object to pass to the visitor.
*/
traverse<C>(visitor: DAGVisitor<T, C>, context: C): void;
private ensureNode;
private isAcyclic;
}
declare function createDAG<T extends Identifiable>(): DAGraph<T>;
export * from './lib/formatVisitors';
export type { DAGraph, Identifiable, DAGVisitor, TraversalState };
export default createDAG;
export { createDAG };