Class: Eco::API::UseCases::GraphQL::Helpers::Location::Command::Diffs::Stages::Sortable::RelationSafeSort
- Inherits:
-
Object
- Object
- Eco::API::UseCases::GraphQL::Helpers::Location::Command::Diffs::Stages::Sortable::RelationSafeSort
- Defined in:
- lib/eco/api/usecases/graphql/helpers/location/command/diffs/stages/sortable/relation_safe_sort.rb
Overview
Class that provided elements that may have a relationship
with a provided block
that compares two single elements (<==>
)
it returns the sorted list of the elements in a safe way
and by keeping the original order when <==>
returns 0
Instance Attribute Summary collapse
-
#cluster_mode ⇒ Object
readonly
Returns the value of attribute cluster_mode.
-
#list ⇒ Object
readonly
Returns the value of attribute list.
Instance Method Summary collapse
- #clustered? ⇒ Boolean
-
#initialize(list, cluster_mode: nil, &block) ⇒ RelationSafeSort
constructor
A new instance of RelationSafeSort.
-
#sort {|a, b| ... } ⇒ Object
When the comparer
<=>
returns0
, it still ensures the order is correct Please notice that nativesort
is not stable when<=>
can return0
.
Constructor Details
#initialize(list, cluster_mode: nil, &block) ⇒ RelationSafeSort
Returns a new instance of RelationSafeSort.
16 17 18 19 20 |
# File 'lib/eco/api/usecases/graphql/helpers/location/command/diffs/stages/sortable/relation_safe_sort.rb', line 16 def initialize(list, cluster_mode: nil, &block) @list = list @cluster_mode = clusterer_class.mode(cluster_mode) if cluster_mode @comparer = block end |
Instance Attribute Details
#cluster_mode ⇒ Object (readonly)
Returns the value of attribute cluster_mode.
10 11 12 |
# File 'lib/eco/api/usecases/graphql/helpers/location/command/diffs/stages/sortable/relation_safe_sort.rb', line 10 def cluster_mode @cluster_mode end |
#list ⇒ Object (readonly)
Returns the value of attribute list.
9 10 11 |
# File 'lib/eco/api/usecases/graphql/helpers/location/command/diffs/stages/sortable/relation_safe_sort.rb', line 9 def list @list end |
Instance Method Details
#clustered? ⇒ Boolean
22 23 24 |
# File 'lib/eco/api/usecases/graphql/helpers/location/command/diffs/stages/sortable/relation_safe_sort.rb', line 22 def clustered? !!@cluster_mode end |
#sort {|a, b| ... } ⇒ Object
When the comparer <=>
returns 0
, it still ensures the order is correct
Please notice that native sort
is not stable when <=>
can return 0
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/eco/api/usecases/graphql/helpers/location/command/diffs/stages/sortable/relation_safe_sort.rb', line 29 def sort return list.dup if list.count <= 1 # treeifying we ensure correct order (parent, children) pending = parents_hash.dup treeify = proc do |item| next item unless (children = pending.delete(item)) {item => children.map {|child| treeify.call(child)}} end sorted_tree = top_parents.each_with_object(unpaired) do |item, tree| next unless pending.key?(item) tree << treeify.call(item) end flatten(sorted_tree) end |