Created
September 20, 2017 09:18
-
-
Save apaleslimghost/3cf89d4ebb1b03bf769ff1960bb74d2b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function toposort(nodes, edges) { | |
var cursor = nodes.length | |
, sorted = new Array(cursor) | |
, visited = {} | |
, i = cursor | |
while (i--) { | |
if (!visited[i]) visit(nodes[i], i, []) | |
} | |
return sorted | |
function visit(node, i, predecessors) { | |
if(predecessors.indexOf(node) >= 0) { | |
throw new Error('Cyclic dependency: '+JSON.stringify(node)) | |
} | |
if (!~nodes.indexOf(node)) { | |
throw new Error('Found unknown node. Make sure to provided all involved nodes. Unknown node: '+JSON.stringify(node)) | |
} | |
if (visited[i]) return; | |
visited[i] = true | |
// outgoing edges | |
var outgoing = edges.filter(function(edge){ | |
return edge[0] === node | |
}) | |
if (i = outgoing.length) { | |
var preds = predecessors.concat(node) | |
do { | |
var child = outgoing[--i][1] | |
visit(child, nodes.indexOf(child), preds) | |
} while (i) | |
} | |
sorted[--cursor] = node | |
} | |
} | |
module.exports = toposort; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment