1 | ;
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | /*-----------------------------------------------------------------------------
|
4 | | Copyright (c) 2014-2017, PhosphorJS Contributors
|
5 | |
|
6 | | Distributed under the terms of the BSD 3-Clause License.
|
7 | |
|
8 | | The full license is in the file LICENSE, distributed with this software.
|
9 | |----------------------------------------------------------------------------*/
|
10 | var iter_1 = require("./iter");
|
11 | /**
|
12 | * Topologically sort an iterable of edges.
|
13 | *
|
14 | * @param edges - The iterable or array-like object of edges to sort.
|
15 | * An edge is represented as a 2-tuple of `[fromNode, toNode]`.
|
16 | *
|
17 | * @returns The topologically sorted array of nodes.
|
18 | *
|
19 | * #### Notes
|
20 | * If a cycle is present in the graph, the cycle will be ignored and
|
21 | * the return value will be only approximately sorted.
|
22 | *
|
23 | * #### Example
|
24 | * ```typescript
|
25 | * import { topologicSort } from '@phosphor/algorithm';
|
26 | *
|
27 | * let data = [
|
28 | * ['d', 'e'],
|
29 | * ['c', 'd'],
|
30 | * ['a', 'b'],
|
31 | * ['b', 'c']
|
32 | * ];
|
33 | *
|
34 | * topologicSort(data); // ['a', 'b', 'c', 'd', 'e']
|
35 | */
|
36 | function topologicSort(edges) {
|
37 | // Setup the shared sorting state.
|
38 | var sorted = [];
|
39 | var visited = new Set();
|
40 | var graph = new Map();
|
41 | // Add the edges to the graph.
|
42 | iter_1.each(edges, addEdge);
|
43 | // Visit each node in the graph.
|
44 | graph.forEach(function (v, k) { visit(k); });
|
45 | // Return the sorted results.
|
46 | return sorted;
|
47 | // Add an edge to the graph.
|
48 | function addEdge(edge) {
|
49 | var fromNode = edge[0], toNode = edge[1];
|
50 | var children = graph.get(toNode);
|
51 | if (children) {
|
52 | children.push(fromNode);
|
53 | }
|
54 | else {
|
55 | graph.set(toNode, [fromNode]);
|
56 | }
|
57 | }
|
58 | // Recursively visit the node.
|
59 | function visit(node) {
|
60 | if (visited.has(node)) {
|
61 | return;
|
62 | }
|
63 | visited.add(node);
|
64 | var children = graph.get(node);
|
65 | if (children) {
|
66 | children.forEach(visit);
|
67 | }
|
68 | sorted.push(node);
|
69 | }
|
70 | }
|
71 | exports.topologicSort = topologicSort;
|