From 4730ac916782c03cde9cdc529a19569e0000ebc8 Mon Sep 17 00:00:00 2001 From: tintinthong Date: Fri, 3 Apr 2020 22:07:05 +0800 Subject: [PATCH 1/2] Add numberOfLevel function --- lib/dep_graph.js | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/lib/dep_graph.js b/lib/dep_graph.js index 1954a62..15aa8de 100644 --- a/lib/dep_graph.js +++ b/lib/dep_graph.js @@ -177,6 +177,34 @@ DepGraph.prototype = { this.incomingEdges[to].splice(idx, 1); } } + }, + /** + * Get the height of a tree + * https://en.wikipedia.org/wiki/Tree_(graph_theory) + */ + numberOfLevel: function() { + var source = this + var outgoingEdges = this.outgoingEdges + if(this.circular){ + console.log("numberOfLevel only works on trees") + return + } + var keys = Object.keys(source.nodes) + var out = 0 + keys.forEach(function(n){ + var result = []; + var DFS = createDFS( + outgoingEdges, + false, + result, + false + ); + DFS(n); + if(result.length > out) { + out = result.length + } + }) + return out }, /** * Return a clone of the dependency graph. If any custom data is attached From a65af80ef84be5ea905f0f697e10029c320f1133 Mon Sep 17 00:00:00 2001 From: tintinthong Date: Sat, 4 Apr 2020 03:23:30 +0800 Subject: [PATCH 2/2] Add getNodesEachLevel --- lib/dep_graph.js | 55 +++++++++++++++++++++++++++--------------------- 1 file changed, 31 insertions(+), 24 deletions(-) diff --git a/lib/dep_graph.js b/lib/dep_graph.js index 15aa8de..8ffe7ef 100644 --- a/lib/dep_graph.js +++ b/lib/dep_graph.js @@ -178,33 +178,40 @@ DepGraph.prototype = { } } }, - /** - * Get the height of a tree - * https://en.wikipedia.org/wiki/Tree_(graph_theory) + /** + * Combines all outgoingEdges of list of nodes */ - numberOfLevel: function() { - var source = this - var outgoingEdges = this.outgoingEdges + getNodesNextLevel: function(nodes) { + var source = this; + var nodesInLevel = [] + for (i = 0; i < nodes.length; i++) { + nodesInLevel = nodesInLevel.concat(source.outgoingEdges[nodes[i]]) + } + return [...new Set(nodesInLevel)] + }, + /** + * Get nodes at each level + * .e.g getNodesEachLevel() + */ + getNodesEachLevel: function(nodes, out, level) { if(this.circular){ - console.log("numberOfLevel only works on trees") - return + throw new Error("getNodesEachLevel only works for trees") } - var keys = Object.keys(source.nodes) - var out = 0 - keys.forEach(function(n){ - var result = []; - var DFS = createDFS( - outgoingEdges, - false, - result, - false - ); - DFS(n); - if(result.length > out) { - out = result.length - } - }) - return out + if(out == undefined){ + out = [] + } + if(nodes == undefined){ + nodes = [Object.keys(this.nodes)[0]] //set root + out.push(nodes) + level = 0 + } + if(this.getNodesNextLevel(nodes).length == 0){ + return out + }else{ + out.push(this.getNodesNextLevel(nodes)) + } + level++ + return this.getNodesEachLevel(out[level], out, level) }, /** * Return a clone of the dependency graph. If any custom data is attached