Class: TimeFrame::Uniter

Inherits:
Object
  • Object
show all
Defined in:
lib/time_frame/time_frame_uniter.rb

Overview

Creates a union of many time_frame’s. You can request a sorted collection by the min Time value.

Instance Method Summary collapse

Constructor Details

#initialize(time_frames, options = {}) ⇒ Uniter

Returns a new instance of Uniter.



6
7
8
9
# File 'lib/time_frame/time_frame_uniter.rb', line 6

def initialize(time_frames, options = {})
  @time_frames = time_frames.reject(&:empty?)
  @sorted = options[:sorted]
end

Instance Method Details

#uniteObject



11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/time_frame/time_frame_uniter.rb', line 11

def unite
  frames = @sorted ? @time_frames : @time_frames.sort_by(&:min)
  frames.each_with_object([]) do |next_time_frame, result|
    last_time_frame = result.last
    if last_time_frame && last_time_frame.cover?(next_time_frame.min)
      max = [last_time_frame.max, next_time_frame.max].max
      result[-1] = TimeFrame.new(min: last_time_frame.min, max: max)
    else
      result << next_time_frame
    end
  end
end