diff --git a/lib/Graph.js b/lib/Graph.js index 3a4ee04..c4edfb8 100644 --- a/lib/Graph.js +++ b/lib/Graph.js @@ -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;