1.0.0 • Published 9 years ago
@tomvlk/dependency-graph v1.0.0
Dependency Graph
Simple dependency graph
Overview
This is a simple dependency graph useful for determining the order to do a list of things that depend on certain items being done before they are.
To use, npm install dependency-graph and then require('dependency-graph').DepGraph
API
DepGraph
Nodes in the graph are just simple strings with optional data associated with them.
addNode(name, data)- add a node in the graph with optional data. Ifdatais not given,namewill be used as dataremoveNode(name)- remove a node from the graphhasNode(name)- check if a node exists in the graphgetNodeData(name)- get the data associated with a node (will throw an Error if the node does not exist)setNodeData(name, data)- set the data for an existing node (will throw an Error if the node does not exist)addDependency(from, to)- add a dependency between two nodes (will throw an Error if one of the nodes does not exist)removeDependency(from, to)- remove a dependency between two nodesdependenciesOf(name, leavesOnly)- get an array containing the nodes that the specified node depends on (transitively). IfleavesOnlyis true, only nodes that do not depend on any other nodes will be returned in the array.dependantsOf(name, leavesOnly)- get an array containing the nodes that depend on the specified node (transitively). IfleavesOnlyis true, only nodes that do not have any dependants will be returned in the array.overallOrder(leavesOnly)- construct the overall processing order for the dependency graph. IfleavesOnlyis true, only nodes that do not depend on any other nodes will be returned.
Dependency Cycles are detected when running dependenciesOf, dependantsOf, and overallOrder and if one is found, an error will be thrown that includes what the cycle was in the message: e.g. Dependency Cycle Found: a -> b -> c -> a.
Examples
var DepGraph = require('dependency-graph').DepGraph;
var graph = new DepGraph();
graph.addNode('a');
graph.addNode('b');
graph.addNode('c');
graph.addDependency('a', 'b');
graph.addDependency('b', 'c');
graph.dependenciesOf('a'); // ['c', 'b']
graph.dependenciesOf('b'); // ['c']
graph.dependantsOf('c'); // ['a', 'b']
graph.overallOrder(); // ['c', 'b', 'a']
graph.overallOrder(true); // ['c']
graph.addNode('d', 'data');
graph.getNodeData('d'); // 'data'
graph.setNodeData('d', 'newData');
graph.getNodeData('d'); // 'newData'