Skip to content

Commit

Permalink
extract flatten_arranged_nodes
Browse files Browse the repository at this point in the history
this is the part responsible for taking a tree and producing an array of nodes
with the parent node before the children

Since children is always a hash, this will never enter the sorting code
and never require the block. so the sorting and the &block was dropped.

This works because ruby enumerates the hashes with insert order (no need to sort again)
  • Loading branch information
kbrock committed Mar 4, 2023
1 parent 9ed5665 commit 8414d90
Showing 1 changed file with 15 additions and 6 deletions.
21 changes: 15 additions & 6 deletions lib/ancestry/class_methods.rb
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,20 @@ def arrange_nodes(nodes)
end
end

# convert a hash of the form {node => children} to an array of nodes, child first
# modifies input hash
#
# @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
end
end

# Arrangement to nested array for serialization
# You can also supply your own serialization logic using blocks
# also allows you to pass the order just as you can pass it to the arrange method
Expand Down Expand Up @@ -105,12 +119,7 @@ def sort_by_ancestry(nodes, &block)
arranged = arrange_nodes(presorted_nodes)
end

arranged.inject([]) do |sorted_nodes, pair|
node, children = pair
sorted_nodes << node
sorted_nodes += sort_by_ancestry(children, &block) unless children.blank?
sorted_nodes
end
flatten_arranged_nodes(arranged)
end

# Integrity checking
Expand Down

0 comments on commit 8414d90

Please sign in to comment.