forked from datavis-tech/graph-data-structure
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
327 lines (281 loc) · 8.12 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
// A graph data structure with depth-first search and topological sort.
module.exports = function Graph(serialized){
// The returned graph instance.
var graph = {
addNode: addNode,
removeNode: removeNode,
nodes: nodes,
adjacent: adjacent,
addEdge: addEdge,
removeEdge: removeEdge,
setEdgeWeight: setEdgeWeight,
getEdgeWeight: getEdgeWeight,
indegree: indegree,
outdegree: outdegree,
depthFirstSearch: depthFirstSearch,
topologicalSort: topologicalSort,
shortestPath: shortestPath,
serialize: serialize,
deserialize: deserialize
};
// The adjacency list of the graph.
// Keys are node ids.
// Values are adjacent node id arrays.
var edges = {};
// The weights of edges.
// Keys are string encodings of edges.
// Values are weights (numbers).
var edgeWeights = {};
// If a serialized graph was passed into the constructor, deserialize it.
if(serialized){
deserialize(serialized);
}
// Adds a node to the graph.
// If node was already added, this function does nothing.
// If node was not already added, this function sets up an empty adjacency list.
function addNode(node){
edges[node] = adjacent(node);
return graph;
}
// Removes a node from the graph.
// Also removes incoming and outgoing edges.
function removeNode(node){
// Remove incoming edges.
Object.keys(edges).forEach(function (u){
edges[u].forEach(function (v){
if(v === node){
removeEdge(u, v);
}
});
});
// Remove outgoing edges (and signal that the node no longer exists).
delete edges[node];
return graph;
}
// Gets the list of nodes that have been added to the graph.
function nodes(){
var nodeSet = {};
Object.keys(edges).forEach(function (u){
nodeSet[u] = true;
edges[u].forEach(function (v){
nodeSet[v] = true;
});
});
return Object.keys(nodeSet);
}
// Gets the adjacent node list for the given node.
// Returns an empty array for unknown nodes.
function adjacent(node){
return edges[node] || [];
}
// Computes a string encoding of an edge,
// for use as a key in an object.
function encodeEdge(u, v){
return u + "|" + v;
}
// Sets the weight of the given edge.
function setEdgeWeight(u, v, weight){
edgeWeights[encodeEdge(u, v)] = weight;
return graph;
}
// Gets the weight of the given edge.
// Returns 1 if no weight was previously set.
function getEdgeWeight(u, v){
var weight = edgeWeights[encodeEdge(u, v)];
return weight === undefined ? 1 : weight;
}
// Adds an edge from node u to node v.
// Implicitly adds the nodes if they were not already added.
function addEdge(u, v, weight){
addNode(u);
addNode(v);
adjacent(u).push(v);
if (weight !== undefined) {
setEdgeWeight(u, v, weight);
}
return graph;
}
// Removes the edge from node u to node v.
// Does not remove the nodes.
// Does nothing if the edge does not exist.
function removeEdge(u, v){
if(edges[u]){
edges[u] = adjacent(u).filter(function (_v){
return _v !== v;
});
}
return graph;
}
// Computes the indegree for the given node.
// Not very efficient, costs O(E) where E = number of edges.
function indegree(node){
var degree = 0;
function check(v){
if(v === node){
degree++;
}
}
Object.keys(edges).forEach(function (u){
edges[u].forEach(check);
});
return degree;
}
// Computes the outdegree for the given node.
function outdegree(node){
return node in edges ? edges[node].length : 0;
}
// Depth First Search algorithm, inspired by
// Cormen et al. "Introduction to Algorithms" 3rd Ed. p. 604
// This variant includes an additional option
// `includeSourceNodes` to specify whether to include or
// exclude the source nodes from the result (true by default).
// If `sourceNodes` is not specified, all nodes in the graph
// are used as source nodes.
function depthFirstSearch(sourceNodes, includeSourceNodes){
if(!sourceNodes){
sourceNodes = nodes();
}
if(typeof includeSourceNodes !== "boolean"){
includeSourceNodes = true;
}
var visited = {};
var nodeList = [];
function DFSVisit(node){
if(!visited[node]){
visited[node] = true;
adjacent(node).forEach(DFSVisit);
nodeList.push(node);
}
}
if(includeSourceNodes){
sourceNodes.forEach(DFSVisit);
} else {
sourceNodes.forEach(function (node){
visited[node] = true;
});
sourceNodes.forEach(function (node){
adjacent(node).forEach(DFSVisit);
});
}
return nodeList;
}
// The topological sort algorithm yields a list of visited nodes
// such that for each visited edge (u, v), u comes before v in the list.
// Amazingly, this comes from just reversing the result from depth first search.
// Cormen et al. "Introduction to Algorithms" 3rd Ed. p. 613
function topologicalSort(sourceNodes, includeSourceNodes){
return depthFirstSearch(sourceNodes, includeSourceNodes).reverse();
}
// Dijkstra's Shortest Path Algorithm.
// Cormen et al. "Introduction to Algorithms" 3rd Ed. p. 658
// Variable and function names correspond to names in the book.
function shortestPath(source, destination){
// Upper bounds for shortest path weights from source.
var d = {};
// Predecessors.
var p = {};
// Poor man's priority queue, keyed on d.
var q = {};
function initializeSingleSource(){
nodes().forEach(function (node){
d[node] = Infinity;
});
if (d[source] !== Infinity) {
throw new Error("Source node is not in the graph");
}
if (d[destination] !== Infinity) {
throw new Error("Destination node is not in the graph");
}
d[source] = 0;
}
// Adds entries in q for all nodes.
function initializePriorityQueue(){
nodes().forEach(function (node){
q[node] = true;
});
}
// Returns true if q is empty.
function priorityQueueEmpty(){
return Object.keys(q).length === 0;
}
// Linear search to extract (find and remove) min from q.
function extractMin(){
var min = Infinity;
var minNode;
Object.keys(q).forEach(function(node){
if (d[node] < min) {
min = d[node];
minNode = node;
}
});
if (minNode === undefined) {
// If we reach here, there's a disconnected subgraph, and we're done.
q = {};
return null;
}
delete q[minNode];
return minNode;
}
function relax(u, v){
var w = getEdgeWeight(u, v);
if (d[v] > d[u] + w) {
d[v] = d[u] + w;
p[v] = u;
}
}
function dijkstra(){
initializeSingleSource();
initializePriorityQueue();
while(!priorityQueueEmpty()){
var u = extractMin();
adjacent(u).forEach(function (v){
relax(u, v);
});
}
}
// Assembles the shortest path by traversing the
// predecessor subgraph from destination to source.
function path(){
var nodeList = [];
var node = destination;
while(p[node]){
nodeList.push(node);
node = p[node];
}
if (node !== source) {
throw new Error("No path found");
}
nodeList.push(node);
nodeList.reverse();
return nodeList;
}
dijkstra();
return path();
}
// Serializes the graph.
function serialize(){
var serialized = {
nodes: nodes().map(function (id){
return { id: id };
}),
links: []
};
serialized.nodes.forEach(function (node){
var source = node.id;
adjacent(source).forEach(function (target){
serialized.links.push({
source: source,
target: target
});
});
});
return serialized;
}
// Deserializes the given serialized graph.
function deserialize(serialized){
serialized.nodes.forEach(function (node){ addNode(node.id); });
serialized.links.forEach(function (link){ addEdge(link.source, link.target); });
return graph;
}
return graph;
}