Sha256: 309ccd29cc021254537b073c7271acd22d6d1b43d1b24c52986eeb6eded583ea

Contents?: true

Size: 563 Bytes

Versions: 10

Compression:

Stored size: 563 Bytes

Contents

# frozen_string_literal: true

module ::Enumerable

  # A stable sort will preserve the original order of two elements if their sort keys are identical.

  def stable_sort
    n = -1
    if block_given?
      collect {|x| n += 1; [x, n]
      }.sort! {|a, b|
        c = yield a[0], b[0]
        if c.nonzero? then c else a[1] <=> b[1] end
      }.collect! {|x| x[0]}
    else
      sort_by {|x| n += 1; [x, n]}
    end
  end

  def stable_sort_by
    block_given? or return enum_for(:stable_sort_by)
    n = -1
    sort_by {|x| n += 1; [(yield x), n]}
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
invoca-utils-0.6.0 lib/invoca/utils/stable_sort.rb
invoca-utils-0.5.1 lib/invoca/utils/stable_sort.rb
invoca-utils-0.5.0 lib/invoca/utils/stable_sort.rb
invoca-utils-0.4.1 lib/invoca/utils/stable_sort.rb
invoca-utils-0.4.0 lib/invoca/utils/stable_sort.rb
invoca-utils-0.3.0 lib/invoca/utils/stable_sort.rb
invoca-utils-0.2.0 lib/invoca/utils/stable_sort.rb
invoca-utils-0.2.0.pre.1 lib/invoca/utils/stable_sort.rb
invoca-utils-0.1.1 lib/invoca/utils/stable_sort.rb
invoca-utils-0.1.0 lib/invoca/utils/stable_sort.rb