Skip to content

Commit 5ac5e9a

Browse files
authored
Update README.md
First pass docs update
1 parent d9785de commit 5ac5e9a

1 file changed

Lines changed: 36 additions & 80 deletions

File tree

README.md

Lines changed: 36 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
A [graph data structure](<https://en.wikipedia.org/wiki/Graph_(abstract_data_type)>) with [topological sort](https://en.wikipedia.org/wiki/Topological_sorting).
44

5-
This library provides a minimalist implementation of a directed graph data structure. Nodes are represented by unique strings. Internally, an [adjacency list](https://en.wikipedia.org/wiki/Adjacency_list) is used to represent nodes and edges.
5+
This library provides a minimalist implementation of a directed graph data structure. Nodes are represented by unique strings or any other object. Internally, an [adjacency list](https://en.wikipedia.org/wiki/Adjacency_list) is used to represent nodes and edges.
66

77
The primary use case for this library is in implementing [dataflow programming](https://en.wikipedia.org/wiki/Dataflow_programming) or [reactive programming](https://en.wikipedia.org/wiki/Reactive_programming). The key algorithm necessary for these is topological sorting, to get an ordering of nodes such that for each edge (**u** -> **v**), **u** comes before **v** in the sorted order. The topological sorting algorithm exposed here has modifications useful for computing the order in which functions in a data flow graph should be executed, namely specifying source nodes for propagation and specifying to exclude the source nodes themselves from the result.
88

@@ -23,17 +23,17 @@ This library is distributed only via [NPM](npmjs.com). Install by running
2323
Require it in your code like this.
2424

2525
```javascript
26-
const { Graph } = require('graph-data-structure');
26+
const { Graph, serializeGraph, deserializeGraph, topologicalSort, shortestPath } = require('graph-data-structure');
2727
```
2828

2929
## Examples
3030

3131
### ABC
3232

33-
To create a graph instance, invoke **[Graph](#graph)** as a constructor function.
33+
To create a graph instance, instantiate **[Graph](#graph)** as a class.
3434

3535
```javascript
36-
var graph = Graph();
36+
var graph = new Graph();
3737
```
3838

3939
Add some nodes and edges with **[addNode](#add-node)** and **[addEdge](#add-edge)**.
@@ -52,10 +52,10 @@ graph.addEdge('b', 'c');
5252

5353
Now we have the following graph. <img src="https://cloud.githubusercontent.com/assets/68416/15385597/44a10522-1dc0-11e6-9054-2150f851db46.png">
5454

55-
[Topological sorting](https://en.wikipedia.org/wiki/Topological_sorting) can be done by invoking **[topologicalSort](#topological-sort)** like this.
55+
[Topological sorting](https://en.wikipedia.org/wiki/Topological_sorting) can be done by invoking the standalone function **[topologicalSort](#topological-sort)** like this.
5656

5757
```javascript
58-
graph.topologicalSort(); // Returns ["a", "b", "c"]
58+
topologicalSort(graph); // Returns ["a", "b", "c"]
5959
```
6060

6161
### Getting Dressed
@@ -67,8 +67,8 @@ Here's an example of topological sort with getting dressed (from Cormen et al. "
6767
</p>
6868

6969
```javascript
70-
var graph = Graph()
71-
.addEdge('socks', 'shoes')
70+
var graph = new Graph();
71+
graph.addEdge('socks', 'shoes')
7272
.addEdge('shirt', 'belt')
7373
.addEdge('shirt', 'tie')
7474
.addEdge('tie', 'jacket')
@@ -78,7 +78,7 @@ var graph = Graph()
7878
.addEdge('pants', 'belt');
7979

8080
// prints [ "underpants", "pants", "shirt", "tie", "belt", "jacket", "socks", "shoes" ]
81-
console.log(graph.topologicalSort());
81+
console.log(topologicalSort(graph));
8282
```
8383

8484
For more detailed example code that shows more methods, have a look at the [tests](https://github.com/datavis-tech/graph-data-structure/blob/master/test.js).
@@ -98,29 +98,29 @@ For more detailed example code that shows more methods, have a look at the [test
9898

9999
Constructs an instance of the graph data structure.
100100

101-
The optional argument _serialized_ is a serialized graph that may have been generated by **[serialize](#serialize)**. If _serialized_ is present, it is deserialized by invoking **[deserialize](#deserialize)**.
101+
The optional argument _serialized_ is a serialized graph that may have been generated by **[serializeGraph](#serializeGraph)**. If _serialized_ is present, it is deserialized by invoking **[deserializeGraph](#deserializeGraph)**.
102102

103103
### Adding and Removing Nodes
104104

105105
<a name="add-node" href="#add-node">#</a> <i>graph</i>.<b>addNode</b>(<i>node</i>)
106106

107-
Adds a node to the graph. Returns _graph_ to support method chaining. The argument _node_ is a string identifier that uniquely identifies the node within this graph instance. If a node with the same identifier was already added to the graph, this function does nothing.
107+
Adds a node to the graph. Returns _graph_ to support method chaining. The argument _node_ can be any object or string that uniquely identifies the node within this graph instance. If a node with the same identifier was already added to the graph, this function does nothing.
108108

109109
<a name="remove-node" href="#remove-node">#</a> <i>graph</i>.<b>removeNode</b>(<i>node</i>)
110110

111-
Removes the specified node. Returns _graph_ to support method chaining. The argument _node_ is a string identifier for the node to remove. This function also removes all edges connected to the specified node, both incoming and outgoing.
111+
Removes the specified node. Returns _graph_ to support method chaining. The argument _node_ is a string or object identifier for the node to remove. This function also removes all edges connected to the specified node, both incoming and outgoing.
112112

113113
### Adding and Removing Edges
114114

115115
<a name="add-edge" href="#add-edge">#</a> <i>graph</i>.<b>addEdge</b>(<i>u</i>, <i>v</i>[,<i>weight</i>])
116116

117-
Adds an edge from node _u_ to node _v_. Returns _graph_ to support method chaining. The arguments _u_ and _v_ are string identifiers for nodes. This function also adds _u_ and _v_ as nodes if they were not already added.
117+
Adds an edge from node _u_ to node _v_. Returns _graph_ to support method chaining. The arguments _u_ and _v_ are node references (either objects or strings). This function also adds _u_ and _v_ as nodes if they were not already added.
118118

119119
The last argument _weight_ (optional) specifies the weight of this edge.
120120

121121
<a name="remove-edge" href="#remove-edge">#</a> <i>graph</i>.<b>removeEdge</b>(<i>u</i>, <i>v</i>)
122122

123-
Removes the edge from node _u_ to node _v_. Returns _graph_ to support method chaining. The arguments _u_ and _v_ are string identifiers for nodes. This function does not remove the nodes _u_ and _v_. Does nothing if the edge does not exist.
123+
Removes the edge from node _u_ to node _v_. Returns _graph_ to support method chaining. The arguments _u_ and _v_ are node references. This function does not remove the nodes _u_ and _v_. Does nothing if the edge does not exist.
124124

125125
<a name="has-edge" href="#has-edge">#</a> <i>graph</i>.<b>hasEdge</b>(<i>u</i>, <i>v</i>)
126126

@@ -132,108 +132,64 @@ Returns `true` if there exists an edge from node _u_ to node _v_. Returns `false
132132

133133
Sets the _weight_ (a number) of the edge from node _u_ to node _v_.
134134

135-
<a name="get-edge-weight" href="#get-edge-weight">#</a> <i>graph</i>.<b>getEdgeWeight</b>(<i>u</i>, <i>v</i>, <i>weight</i>)
135+
<a name="get-edge-weight" href="#get-edge-weight">#</a> <i>graph</i>.<b>getEdgeWeight</b>(<i>u</i>, <i>v</i>)
136136

137137
Gets the _weight_ of the edge from node _u_ to node _v_. If no weight was previously set on this edge, then the value 1 is returned.
138138

139139
### Querying the Graph
140140

141-
<a name="nodes" href="#nodes">#</a> <i>graph</i>.<b>nodes</b>()
142-
143-
List all nodes in the graph. Returns an array of node identifier strings.
144-
145141
<a name="adjacent" href="#adjacent">#</a> <i>graph</i>.<b>adjacent</b>(<i>node</i>)
146142

147-
Gets the adjacent node list for the specified node. The argument _node_ is a string identifier for a node. Returns an array of node identifier strings.
148-
149-
The "adjacent node list" is the Array of nodes for which there is an incoming edge from the given node. In other words, for all edges (**u** -> **v**) where **u** is the specified node, all values for **v** are in the adjacent node list.
150-
151-
<a name="indegree" href="#indegree">#</a> <i>graph</i>.<b>indegree</b>(<i>node</i>)
152-
153-
Computes the [indegree](https://en.wikipedia.org/wiki/Directed_graph#Indegree_and_outdegree) (number of incoming edges) for the specified _node_.
154-
155-
<a name="outdegree" href="#outdegree">#</a> <i>graph</i>.<b>outdegree</b>(<i>node</i>)
156-
157-
Computes the [outdegree](https://en.wikipedia.org/wiki/Directed_graph#Indegree_and_outdegree) (number of outgoing edges) for the specified _node_.
143+
Gets the adjacent node list for the specified node. The argument _node_ is a node reference (object or string). Returns a `Set` of adjacent node references or `undefined` if the node is not found.
158144

159145
### Serialization
160146

161-
<a name="serialize" href="#serialize">#</a> <i>graph</i>.<b>serialize</b>()
147+
<a name="serializeGraph" href="#serializeGraph">#</a> <b>serializeGraph</b>(<i>graph</i>)
162148

163149
Serializes the graph. Returns an object with the following properties.
164150

165-
- `nodes` An array of objects, each with an `id` property whose value is a node identifier string.
151+
- `nodes` An array of objects, each representing a node reference.
166152
- `links` An array of objects representing edges, each with the following properties.
167-
- `source` The node identifier string of the source node (**u**).
168-
- `target` The node identifier string of the target node (**v**).
153+
- `source` The node reference of the source node (**u**).
154+
- `target` The node reference of the target node (**v**).
169155
- `weight` The weight of the edge between the source and target nodes.
170156

171157
Here's example code for serializing a graph.
172158

173159
```javascript
174-
var graph = Graph();
160+
var graph = new Graph();
175161
graph.addEdge('a', 'b');
176162
graph.addEdge('b', 'c');
177-
var serialized = graph.serialize();
163+
var serialized = serializeGraph(graph);
178164
```
179165

180-
The following will be the value of `serialized`.
166+
<a name="deserializeGraph" href="#deserializeGraph">#</a> <b>deserializeGraph</b>(<i>serialized</i>)
181167

182-
```json
183-
{
184-
"nodes": [{ "id": "a" }, { "id": "b" }, { "id": "c" }],
185-
"links": [
186-
{ "source": "a", "target": "b", "weight": 1 },
187-
{ "source": "b", "target": "c", "weight": 1 }
188-
]
189-
}
190-
```
191-
192-
This representation conforms to the convention of graph representation when working with D3.js force layouts. See also [d3.simulation.nodes](https://github.com/d3/d3-force#simulation_nodes) and [d3.forceLinks](https://github.com/d3/d3-force#links).
193-
194-
<a name="deserialize" href="#deserialize">#</a> <i>graph</i>.<b>deserialize</b>(<i>serialized</i>)
195-
196-
Deserializes the given serialized graph. Returns _graph_ to support method chaining. The argument _serialized_ is a graph representation with the structure described in **[serialize](#serialize)**. This function iterates over the serialized graph and adds the nodes and links it represents by invoking **[addNode](#add-node)** and **[addEdge](#add-edge)**. The output from **[serialize](#serialize)** can be used as the input to **deserialize**.
168+
Deserializes the given serialized graph. Returns a new _graph_. The argument _serialized_ is a graph representation with the structure described in **[serializeGraph](#serializeGraph)**.
197169

198170
### Graph Algorithms
199171

200-
<a name="dfs" href="#dfs">#</a> <i>graph</i>.<b>depthFirstSearch</b>([<i>sourceNodes</i>][, <i>includesourcenodes</i>][, <i>errorOnCycle</i>])
201-
202-
Performs [Depth-first Search](https://en.wikipedia.org/wiki/Depth-first_search). Returns an array of node identifier strings. The returned array includes nodes visited by the algorithm in the order in which they were visited. Implementation inspired by pseudocode from Cormen et al. "Introduction to Algorithms" 3rd Ed. p. 604.
203-
204-
Arguments:
172+
<a name="topological-sort" href="#topological-sort">#</a> <b>topologicalSort</b>(<i>graph</i>)
205173

206-
- _sourceNodes_ (optional) - An array of node identifier strings. This specifies the subset of nodes to use as the sources of the depth-first search. If _sourceNodes_ is not specified, all **[nodes](#nodes)** in the graph are used as source nodes.
207-
- _includeSourceNodes_ (optional) - A boolean specifying whether or not to include the source nodes in the returned array. If _includeSourceNodes_ is not specified, it is treated as `true` (all source nodes are included in the returned array).
208-
- _errorOnCycle_ (optional) - A boolean indicating that a `CycleError` should be thrown whenever a cycle is first encountered. Defaults to `false`.
174+
Performs [Topological Sort](
209175

210-
<a name="has-cycle" href="#has-cycle">#</a> <i>graph</i>.<b>hasCycle</b>()
211-
212-
Checks if the graph has any cycles. Returns `true` if it does and `false` otherwise.
213-
214-
<a name="lca" href="#lca">#</a> <i>graph</i>.<b>lowestCommonAncestors</b>([<i>node1</i>][, <i>node2</i>])
215-
216-
Performs search of [Lowest common ancestors](https://en.wikipedia.org/wiki/Lowest_common_ancestor). Returns an array of node identifier strings.
217-
218-
Arguments:
219-
220-
- _node1_ (required) - First node.
221-
- _node2_ (required) - Second node.
222-
223-
<a name="topological-sort" href="#topological-sort">#</a> <i>graph</i>.<b>topologicalSort</b>([<i>sourceNodes</i>][, <i>includesourcenodes</i>])
224-
225-
Performs [Topological Sort](https://en.wikipedia.org/wiki/Topological_sorting). Returns an array of node identifier strings. The returned array includes nodes in topologically sorted order. This means that for each visited edge (**u** -> **v**), **u** comes before **v** in the topologically sorted order. Amazingly, this comes from simply reversing the result from depth first search. Inspired by by Cormen et al. "Introduction to Algorithms" 3rd Ed. p. 613.
226-
227-
See **[depthFirstSearch](#dfs)** for documentation of the arguments _sourceNodes_ and _includeSourceNodes_.
176+
https://en.wikipedia.org/wiki/Topological_sorting). Returns an array of node identifier strings. The returned array includes nodes in topologically sorted order. This means that for each visited edge (**u** -> **v**), **u** comes before **v** in the topologically sorted order.
228177

229178
Note: this function raises a `CycleError` when the input is not a DAG.
230179

231-
<a name="shortest-path" href="#shortest-path">#</a> <i>graph</i>.<b>shortestPath</b>(<i>sourceNode</i>, <i>destinationNode</i>)
180+
<a name="shortest-path" href="#shortest-path">#</a> <b>shortestPath</b>(<i>graph</i>, <i>sourceNode</i>, <i>destinationNode</i>)
181+
182+
Performs [Dijkstra's Algorithm](https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm). Returns an object with two properties: `nodes`, an array of node references representing the path, and `weight`, the total weight of the path.
232183

233-
Performs [Dijkstras Algorithm](https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm). Returns an array of node identifier strings. The returned array includes the nodes of the shortest path from source to destination node. The returned array also contains a `weight` property, which is the total weight over all edges in the path. Inspired by by Cormen et al. "Introduction to Algorithms" 3rd Ed. p. 658.
184+
```javascript
185+
var result = shortestPath(graph, 'a', 'c');
186+
console.log(result.nodes); // Prints the array of nodes in the shortest path
187+
console.log(result.weight); // Prints the total weight of the path
188+
```
234189

235190
<p align="center">
236191
<a href="https://datavis.tech/">
237192
<img src="https://cloud.githubusercontent.com/assets/68416/15298394/a7a0a66a-1bbc-11e6-9636-367bed9165fc.png">
238193
</a>
239194
</p>
195+
```

0 commit comments

Comments
 (0)