Skip to content

Commit

Permalink
flatten_arranged_nodes: Don't allocate a arrays per child
Browse files Browse the repository at this point in the history
Since this is in its own method, we no longer have such a big call stack
Also, we are no longer creating a 2 new arrays for every set of children
  • Loading branch information
kbrock committed Mar 4, 2023
1 parent 8414d90 commit 719a457
Showing 1 changed file with 5 additions and 7 deletions.
12 changes: 5 additions & 7 deletions lib/ancestry/class_methods.rb
Original file line number Diff line number Diff line change
Expand Up @@ -63,17 +63,15 @@ def arrange_nodes(nodes)
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
def flatten_arranged_nodes(arranged, nodes = [])
arranged.each do |node, children|
nodes << node
flatten_arranged_nodes(children, nodes) unless children.empty?
end
nodes
end

# Arrangement to nested array for serialization
Expand Down

0 comments on commit 719a457

Please sign in to comment.