Skip to content

Commit

Permalink
use a non-recursive algorithm for sort_by_ancestry
Browse files Browse the repository at this point in the history
  • Loading branch information
kbrock committed Feb 24, 2023
1 parent 9761841 commit 592350a
Showing 1 changed file with 17 additions and 5 deletions.
22 changes: 17 additions & 5 deletions lib/ancestry/class_methods.rb
Original file line number Diff line number Diff line change
Expand Up @@ -68,12 +68,24 @@ def arrange_nodes(nodes)
# @param arranged [Hash{Node => {Node => {}, Node => {}}}] arranged nodes
# @returns [Array[Node]] array of nodes with the parent before the children
def flatten_arranged_nodes(arranged)
arranged.inject([]) do |sorted_nodes, pair|
node, children = pair
sorted_nodes << node
sorted_nodes += flatten_arranged_nodes(children) unless children.blank?
sorted_nodes
nodes = []
stack = []
cur = arranged
while cur.present? || stack.present?
node, children = cur.first
nodes << node
children = cur.delete(node)

if children.present?
# work on children, will continue on current node later
stack.push(cur) if cur.present?
cur = children
elsif cur.empty?
# return to remembered node if done processing current children
cur = stack.pop
end
end
nodes
end

# Arrangement to nested array for serialization
Expand Down

0 comments on commit 592350a

Please sign in to comment.