Class: Eco::API::UseCases::GraphQL::Helpers::Location::Command::Diffs::Stages::Sortable::RelationSafeSort

Inherits:
Object
  • Object
show all
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

Instance Method Summary collapse

Constructor Details

#initialize(list, cluster_mode: nil, &block) ⇒ RelationSafeSort

Returns a new instance of RelationSafeSort.

Parameters:

  • cluster_mode (Boolean) (defaults to: nil)

    whether it should optimize by trying to first treeify and only trying to resolve the by pairings (one to one) the diffs that are hanging from now where. Possible values are :prev or :curr



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_modeObject (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

#listObject (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

Returns:

  • (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

Yields:

  • (a, b)

    elements to be sorted



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