Skip to content

Commit 4a15260

Browse files
committed
Export topological sort
1 parent 8a3c0a0 commit 4a15260

File tree

1 file changed

+31
-36
lines changed

1 file changed

+31
-36
lines changed
Lines changed: 31 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,39 @@
1-
var topologicalSort = (function () {
1+
(function (exports) {
22
'use strict';
33

4-
function topologicalSortHelper(node, visited, temp, graph, result) {
5-
temp[node] = true;
6-
var neighbors = graph[node];
7-
for (var i = 0; i < neighbors.length; i += 1) {
8-
var n = neighbors[i];
9-
if (temp[n]) {
10-
throw new Error('The graph is not a DAG');
11-
}
12-
if (!visited[n]) {
13-
topologicalSortHelper(n, visited, temp, graph, result);
4+
var topologicalSort = (function () {
5+
6+
function topologicalSortHelper(node, visited, temp, graph, result) {
7+
temp[node] = true;
8+
var neighbors = graph[node];
9+
for (var i = 0; i < neighbors.length; i += 1) {
10+
var n = neighbors[i];
11+
if (temp[n]) {
12+
throw new Error('The graph is not a DAG');
13+
}
14+
if (!visited[n]) {
15+
topologicalSortHelper(n, visited, temp, graph, result);
16+
}
1417
}
18+
temp[node] = false;
19+
visited[node] = true;
20+
result.push(node);
1521
}
16-
temp[node] = false;
17-
visited[node] = true;
18-
result.push(node);
19-
}
2022

21-
return function (graph) {
22-
var result = [],
23-
visited = [],
24-
temp = [];
25-
for (var node in graph) {
26-
if (!visited[node] && !temp[node]) {
27-
topologicalSortHelper(node, visited, temp, graph, result);
23+
return function (graph) {
24+
var result = [],
25+
visited = [],
26+
temp = [];
27+
for (var node in graph) {
28+
if (!visited[node] && !temp[node]) {
29+
topologicalSortHelper(node, visited, temp, graph, result);
30+
}
2831
}
29-
}
30-
return result.reverse();
31-
};
32-
}());
32+
return result.reverse();
33+
};
34+
}());
35+
36+
exports.topologicalSort = topologicalSort;
3337

34-
var graph = {
35-
'0': ['1', '2'],
36-
'1': ['2', '4'],
37-
'2': ['3'],
38-
'3': [],
39-
'4': ['5', '6'],
40-
'5': [],
41-
'6': ['3']
42-
};
38+
}(typeof exports === 'undefined' ? window : exports));
4339

44-
console.log(topologicalSort(graph));

0 commit comments

Comments
 (0)