-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathinterval.rb
69 lines (52 loc) · 1.44 KB
/
interval.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# frozen_string_literal: true
module Biz
class Interval
extend Forwardable
include Comparable
def self.to_hours(intervals)
intervals.each_with_object(
Hash.new do |hours, wday| hours.store(wday, {}) end
) do |interval, hours|
hours[interval.wday_symbol].store(*interval.endpoints.map(&:timestamp))
end
end
def initialize(start_time, end_time, time_zone)
@start_time = start_time
@end_time = end_time
@time_zone = time_zone
end
attr_reader :start_time,
:end_time,
:time_zone
delegate wday_symbol: :start_time
def endpoints
[start_time, end_time]
end
def empty?
start_time >= end_time
end
def contains?(time)
(start_time...end_time).cover?(
WeekTime.from_time(Time.new(time_zone).local(time))
)
end
def to_time_segment(week)
TimeSegment.new(
*endpoints.map { |endpoint|
Time.new(time_zone).during_week(week, endpoint)
}
)
end
def &(other)
lower_bound = [self, other].map(&:start_time).max
upper_bound = [self, other].map(&:end_time).min
self.class.new(lower_bound, [lower_bound, upper_bound].max, time_zone)
end
private
def <=>(other)
return unless other.is_a?(self.class)
[start_time, end_time, time_zone] <=>
[other.start_time, other.end_time, other.time_zone]
end
end
end