Skip to content

Commit

Permalink
trim down sort
Browse files Browse the repository at this point in the history
This is no longer creating unique arrays at ever level.

This does not change the sorting algorithm.
It is still sorting levels by id. not optimal
  • Loading branch information
kbrock committed Feb 24, 2023
1 parent bdb9143 commit 92a8d99
Showing 1 changed file with 12 additions and 15 deletions.
27 changes: 12 additions & 15 deletions lib/ancestry/class_methods.rb
Original file line number Diff line number Diff line change
Expand Up @@ -89,29 +89,26 @@ def tree_view(column, data = nil)
end

# Pseudo-preordered array of nodes. Children will always follow parents,
def sort_by_ancestry(nodes, &block)
arranged = nodes if nodes.is_a?(Hash)

unless arranged
# This is deterministic unless the parents are missing *and* a sort block is specified
def sort_by_ancestry(nodes, sorted_nodes = [], &block)
# is this a hash or enumerated hash (enumerated hashes are array of arrays)
if nodes.is_a?(Hash) || (nodes.first.is_a?(Array) && nodes.first.size == 2)
arranged = nodes
else
presorted_nodes = nodes.sort do |a, b|
a_cestry, b_cestry = a.ancestry || '0', b.ancestry || '0'

if block_given? && a_cestry == b_cestry
yield a, b
else
a_cestry <=> b_cestry
end
rank = (a.ancestry || '0') <=> (b.ancestry || '0')
rank = yield(a, b) if rank == 0 && block_given?
rank
end

arranged = arrange_nodes(presorted_nodes)
end

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

# Integrity checking
Expand Down

0 comments on commit 92a8d99

Please sign in to comment.