From 08c5f8522539818abd9ab766536a1e92f1477538 Mon Sep 17 00:00:00 2001 From: Kheir Eddine Farfar Date: Fri, 18 Oct 2024 13:34:52 +0200 Subject: [PATCH] refactor: use a stack instead of recursion in Graph.toArray --- lib/Graph.js | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) 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;