var a = new Node("a");
var b = new Node("b");
var c = new Node("c");
var d = new Node("d");
var e = new Node("e");
a.addEdge(b); // a depends on b
a.addEdge(d); // a depends on d
b.addEdge(c); // b depends on c
b.addEdge(e); // b depends on e
c.addEdge(d); // c depends on d
c.addEdge(e); // c depends on e
var resolver = new DependencyResolver();
resolver.resolve(a);
console.log(resolver.nodesResolved);
Last active
December 27, 2015 20:19
-
-
Save jonathanmarvens/7383902 to your computer and use it in GitHub Desktop.
Simple dependency graph resolver. I needed this for a project, so if it can help someone else too, awesome :) . Of course you'll need to modify it for whatever your nodes' edges may be.
This file contains hidden or 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
class CircularReferenceException extends Error | |
constructor: (@message = "Circular dependency detected!") -> | |
@name = "CircularReferenceException" |
This file contains hidden or 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
class DependencyResolver | |
constructor: -> | |
@nodesResolved = [] | |
@nodesUnresolved = [] | |
resolve: (node) -> | |
unresolvedNodeIndex = @nodesUnresolved.length | |
@nodesUnresolved.push node | |
for edge in node.edges | |
if edge not in @nodesResolved | |
if edge not in @nodesUnresolved | |
@resolve edge | |
else | |
throw new CircularReferenceException "Circular dependency detected: #{node.name} -> #{edge.name}." | |
@nodesResolved.push node | |
@nodesUnresolved.splice unresolvedNodeIndex, 1 | |
return |
This file contains hidden or 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
class Node | |
constructor: (@name) -> | |
@edges = [] | |
addEdge: (node) -> | |
@edges.push node | |
return |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment