Module: RangeOperations::Array
- Defined in:
- lib/range_operations/array.rb
Class Method Summary collapse
-
.simplify(ranges) ⇒ Object
Returns a sorted array with overlapping and contiguous items merged.
-
.sort(ranges) ⇒ Object
Returns a new array with the ranges sorted by their .begin value.
-
.subtract(range, subranges) ⇒ Object
Returns an array of ranges resulting from removing from
rangeany parts overlapped by any ofsubranges.
Class Method Details
.simplify(ranges) ⇒ Object
Returns a sorted array with overlapping and contiguous items merged
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
# File 'lib/range_operations/array.rb', line 10 def self.simplify(ranges) straight = ranges.map { |r| RangeOperations::Single.straighten(r) } sorted = straight.sort_by(&:begin) [].tap do |acc| sorted.each do |r| if acc.empty? acc << r else if acc[-1].end < r.begin acc << r else acc << RangeOperations::Pair.merge(acc.pop, r) end end end end end |
.sort(ranges) ⇒ Object
Returns a new array with the ranges sorted by their .begin value
5 6 7 |
# File 'lib/range_operations/array.rb', line 5 def self.sort(ranges) ranges.sort_by(&:begin) end |
.subtract(range, subranges) ⇒ Object
Returns an array of ranges resulting from removing from range any parts overlapped by any of subranges.
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/range_operations/array.rb', line 31 def self.subtract(range, subranges) simple = simplify(subranges) [].tap do |acc| start = range.begin simple.each do |sr| next if sr.end < start if sr.begin > start finish = [sr.begin, range.end].min acc << (start .. finish) end start = sr.end break if start > range.end end if start < range.end acc << (start .. range.end) end end end |