A directed acyclic graph (DAG) implementation in TypeScript.
- Generic Graph Structure: Store any identifiable data in the graph.
- Topological Sort: Iterate over nodes in topological order (dependencies first).
- Cycle Detection: Automatically detects and prevents cycles when adding edges.
- Root Traversal: Efficiently access all root nodes (nodes with no dependencies).
- Graph Reversal: Create a new graph with all edges reversed.
- Depth-First Traversal: Visit nodes with context, parent, depth, and index information.
- TypeScript: Written in TypeScript with full type definitions.
import createDAG from '@sha1n/dagraph';
const dag = createDAG();
dag.addNode({id : 'a'});
dag.addEdge({id : 'b'}, {id : 'a'}); // b -> a
dag.addEdge({id : 'c'}, {id : 'a'}); // c -> a
dag.addEdge({id : 'd'}, {id : 'b'}); // d -> b
// Topological sort
for (const node of dag.topologicalSort()) {
console.log(node.id);
}Any object implementing the Identifiable interface (having an id: string property) can be stored.
import { createDAG, Identifiable } from '@sha1n/dagraph';
type MyThing = {
id: string;
name: string;
doSomething(): void;
};
const myThing: MyThing = {
id: 'a',
name: 'my thing',
doSomething: () => {
console.log('A');
}
};
const myOtherThing: MyThing = {
id: 'b',
name: 'my other thing',
doSomething: () => {
console.log('B');
}
};
const myDAG = createDAG<MyThing>();
// Add nodes explicitly or implicitly via addEdge
myDAG.addEdge(myThing, myOtherThing); // myThing -> myOtherThingUsing pnpm (recommended):
pnpm add @sha1n/dagraphUsing npm:
npm i @sha1n/dagraphUsing yarn:
yarn add @sha1n/dagraphThis project uses pnpm for dependency management.
- Node.js (version specified in
.nvmrcorenginesinpackage.json) - pnpm
-
Install dependencies:
pnpm install
-
Build:
pnpm build
-
Run Tests:
pnpm test -
Lint:
pnpm lint