Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize tree walk to avoid too depth function call stack. #326

Merged
merged 3 commits into from
Feb 21, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions packages/jaeger-ui/src/utils/TreeNode.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,18 @@ export default class TreeNode {
}

walk(fn, depth = 0) {
TreeNode.iterFunction(fn, depth)(this);
this.children.forEach(child => child.walk(fn, depth + 1));
const nodeStack = [];
let actualDepth = depth;
nodeStack.push({ node: this, depth: actualDepth });
while (nodeStack.length) {
const { node, depth: nodeDepth } = nodeStack.pop();
fn(node.value, node, nodeDepth);
actualDepth = nodeDepth + 1;
let i = node.children.length - 1;
while (i >= 0) {
nodeStack.push({ node: node.children[i], depth: actualDepth });
i--;
}
}
}
}
27 changes: 27 additions & 0 deletions packages/jaeger-ui/src/utils/TreeNode.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -264,3 +264,30 @@ it('walk() should iterate over every item once in the right order', () => {

treeRoot.walk(value => expect(value).toBe(++i));
});

it('walk() should iterate over every item and compute the right deep on each node', () => {
/**
* C0
* /
* B0 – C1
* /
* A – B1 – C2
* \
* C3 – D
*/

const nodeA = new TreeNode('A');
const nodeB0 = new TreeNode('B0');
const nodeB1 = new TreeNode('B1');
const nodeC3 = new TreeNode('C3');
const depthMap = { A: 0, B0: 1, B1: 1, C0: 2, C1: 2, C2: 2, C3: 2, D: 3 };
nodeA.addChild(nodeB0);
nodeA.addChild(nodeB0);
nodeA.addChild(nodeB1);
nodeB0.addChild('C0');
nodeB0.addChild('C1');
nodeB1.addChild('C2');
nodeB1.addChild(nodeC3);
nodeC3.addChild('D');
nodeA.walk((value, node, depth) => expect(depth).toBe(depthMap[value]));
});