Skip to content

Commit 592350a

Browse files
committed
use a non-recursive algorithm for sort_by_ancestry
1 parent 9761841 commit 592350a

File tree

1 file changed

+17
-5
lines changed

1 file changed

+17
-5
lines changed

Diff for: lib/ancestry/class_methods.rb

+17-5
Original file line numberDiff line numberDiff line change
@@ -68,12 +68,24 @@ def arrange_nodes(nodes)
6868
# @param arranged [Hash{Node => {Node => {}, Node => {}}}] arranged nodes
6969
# @returns [Array[Node]] array of nodes with the parent before the children
7070
def flatten_arranged_nodes(arranged)
71-
arranged.inject([]) do |sorted_nodes, pair|
72-
node, children = pair
73-
sorted_nodes << node
74-
sorted_nodes += flatten_arranged_nodes(children) unless children.blank?
75-
sorted_nodes
71+
nodes = []
72+
stack = []
73+
cur = arranged
74+
while cur.present? || stack.present?
75+
node, children = cur.first
76+
nodes << node
77+
children = cur.delete(node)
78+
79+
if children.present?
80+
# work on children, will continue on current node later
81+
stack.push(cur) if cur.present?
82+
cur = children
83+
elsif cur.empty?
84+
# return to remembered node if done processing current children
85+
cur = stack.pop
86+
end
7687
end
88+
nodes
7789
end
7890

7991
# Arrangement to nested array for serialization

0 commit comments

Comments
 (0)