lib/abstractivator/enumerable_ext.rb in abstractivator-0.0.19 vs lib/abstractivator/enumerable_ext.rb in abstractivator-0.0.20

- old
+ new

@@ -45,11 +45,11 @@ def self.proc?(x) x.respond_to?(:call) end - def hash_map(get_key, &get_value) + def hash_map(get_key=->x{x}, &get_value) Hash[self.map{|x| [get_key.(x), get_value ? get_value.(x) : x]}] end def outer_join(right, get_left_key, get_right_key, default_value) Enumerable.outer_join(self, right, get_left_key, get_right_key, default_value, default_value) @@ -88,7 +88,17 @@ end def pad_right(n, value=nil, &block) block ||= proc { value } self + ([n-self.size, 0].max).times.map(&block) + end + + def stable_sort(&compare) + compare = compare || ->(a, b){a <=> b} + xis = self.each_with_index.map{|x, i| [x, i]} + sorted = xis.sort do |(a, ai), (b, bi)| + primary = compare.call(a, b) + primary != 0 ? primary : (ai <=> bi) + end + sorted.map(&:first) end end