Sha256: 9dc10a482911be6d9f7ff7a89cec2bbaf7cafbb8b275878b07890a0ab254ae94

Contents?: true

Size: 532 Bytes

Versions: 4

Compression:

Stored size: 532 Bytes

Contents

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

4 entries across 4 versions & 1 rubygems

Version Path
invoca-utils-0.1.0.pre.2 lib/invoca/utils/stable_sort.rb
invoca-utils-0.0.5 lib/invoca/utils/stable_sort.rb
invoca-utils-0.0.4 lib/invoca/utils/stable_sort.rb
invoca-utils-0.0.3 lib/invoca/utils/stable_sort.rb