# TODO Need to incorporate end sentinal inclusion vs. exclusion.

class Range

  # Combine intervals.

  def self.combine(*intervals)
    intype = intervals.first.class
    result = []

    intervals = intervals.collect do |i|
      [i.first, i.last]
    end

    intervals.sort.inject([]) do |result, (from, to)|
      if result.empty? or from > result.last[1]
        result << [from, to]
      elsif to > result.last[1]
        result.last[1] = to
      end
      result
    end

    if intype <= Range
      result.collect{ |i| ((i.first)..(i.last)) }
    else
      result
    end
  end

  # Combine intervals.

  def combine(*intervals)
    Range.combine(self, *intervals)
  end

end




=begin test

  require 'test/unit'

  class TestCombine < Test::Unit::TestCase

    def test_combine_ranges
      r = Range.combine(0..4, 2..6, 6..10, 13..17, 12..19)
      x = [0..10, 12..19] 
      assert_equal(x, r)
    end

    def test_combine_arrays_as_intervals
      r = Range.combine([0, 4], [2, 6], [6, 10], [13, 17], [12, 19])
      x = [[0, 10], [12, 19]] 
      assert_equal(x, r)
    end

  end

=end
