Module: RangeCompressor
- Defined in:
- lib/range_compressor.rb,
lib/range_compressor/version.rb
Constant Summary collapse
- SORTED_SET_CLASSES =
%w[ CharacterSet CharacterSet::Pure ImmutableSet SortedSet ].freeze
- VERSION =
'1.0.0'
Class Method Summary collapse
-
.compress(enum) ⇒ Object
Set#divide is very slow unfortunately, else it would be nice for this: divide { |i, j| (i - j).abs == 1 }.
Class Method Details
.compress(enum) ⇒ Object
Set#divide is very slow unfortunately, else it would be nice for this: divide { |i, j| (i - j).abs == 1 }
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/range_compressor.rb', line 15 def compress(enum) if enum.class.ancestors.none? { |anc| SORTED_SET_CLASSES.include? anc.to_s } require 'set' enum = SortedSet.new(enum) end ranges = [] previous = nil current_start = nil current_end = nil enum.each do |object| if previous.nil? current_start = object elsif previous.next != object # gap found, finalize previous range ranges << (current_start..current_end) current_start = object end current_end = object previous = object end # add final range ranges << (current_start..current_end) if current_start ranges end |