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

refactor: use a stack instead of recursion in Graph.toArray #21

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
20 changes: 15 additions & 5 deletions lib/Graph.js
Original file line number Diff line number Diff line change
Expand Up @@ -141,11 +141,21 @@ Graph.prototype.toArray = function toArray() {
var triples = [];
var data = this.indexPSO;
if(!data) return [];
(function go(data, c){
if(c) Object.keys(data).forEach(function(t){go(data[t], c-1);});
else triples.push(data);
})(data, 3);
return triples;
// Use a stack to avoid recursion
var stack = [{ node: data, depth: 3 }];
while (stack.length > 0) {
var current = stack.pop();
var currentNode = current.node;
var currentDepth = current.depth;
if (currentDepth > 0) {
Object.keys(currentNode).forEach(function (key) {
stack.push({ node: currentNode[key], depth: currentDepth - 1 });
});
} else {
triples.push(currentNode);
}
}
return triples.reverse();
};
Graph.prototype.filter = function filter(cb){
var result = new Graph;
Expand Down