Skip to content

Commit

Permalink
feat: add level property to node
Browse files Browse the repository at this point in the history
  • Loading branch information
ludanxer committed Feb 16, 2020
1 parent 10d401e commit fa177d2
Showing 1 changed file with 26 additions and 1 deletion.
27 changes: 26 additions & 1 deletion lib/graph/GraphTree.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,12 @@ function DFS(node) {
let linkArray = [];
for(let child of node.children) {
const { nodes, links } = DFS(child);

if(nodes.length === 1) child.maxLevel = child.minLevel = 1;
else {
const { maxLevel, minLevel } = calcuLevel(nodes.slice(1));
child.maxLevel = maxLevel + 1;
child.minLevel = minLevel + 1;
}
nodeArray = nodeArray.concat(nodes);

linkArray.push({
Expand All @@ -53,3 +58,23 @@ function DFS(node) {
links: linkArray
}
}

/**
* Calculate node level in the GraphTree
*
* level is calculated from leaf to root
* @param {GraphNode} nodes
*/

function calcuLevel(nodes) {
let maximum = 1;
let minimum = 999;
for(let node of nodes) {
if(node.maxLevel > maximum) maximum = node.maxLevel;
if(node.minLevel < minimum) minimum = node.minLevel;
}
return {
maxLevel: maximum,
minLevel: minimum
};
}

0 comments on commit fa177d2

Please # to comment.