edtf 4.1.1 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/lib/edtf/interval.rb CHANGED
@@ -1,331 +1,201 @@
1
1
  module EDTF
2
2
 
3
- # An interval behaves like a regular Range but is dedicated to EDTF dates.
4
- # Most importantly, intervals use the date's precision when generating
5
- # the set of contained values and for membership tests. All tests are
6
- # implemented without iteration and should therefore be considerably faster
7
- # than if you were to use a regular Range.
3
+ # An interval behaves like a regular Range but is dedicated to EDTF periods.
4
+ # Most importantly, intervals use the precision of their start
5
+ # when generating the set of contained values and for membership tests.
6
+ # All tests are implemented without iteration.
8
7
  #
9
- # For example, the interval "2003/2006" covers the years 2003, 2004, 2005
10
- # and 2006. Converting the interval to an array would result in a an array
11
- # containing exactly four dates with year precision. This is also reflected
12
- # in membership tests.
8
+ # For example, the interval "2003/2006"
9
+ # covers the years 2003, 2004, 2005 and 2006.
10
+ # Converting the interval to an array results in an array
11
+ # containing exactly four dates with year precision.
12
+ # This is also reflected in membership tests.
13
13
  #
14
- # EDTF('2003/2006').length -> 4
14
+ # EDTF('2003/2006').count -> 4
15
15
  #
16
16
  # EDTF('2003/2006').include? EDTF('2004') -> true
17
17
  # EDTF('2003/2006').include? EDTF('2004-03') -> false
18
18
  #
19
19
  # EDTF('2003/2006').cover? EDTF('2004-03') -> true
20
20
  #
21
+ # Each end is a period, :open (no bound, written ..),
22
+ # or :unknown (written empty).
23
+ # The bounds of open or unknown ends are nil.
21
24
  class Interval
22
-
23
- extend Forwardable
24
-
25
- include Comparable
26
25
  include Enumerable
26
+ # After Enumerable, so ActiveSupport's Enumerable#as_json doesn't win.
27
+ include Period
27
28
 
28
- # Intervals delegate hash calculation to Ruby Range
29
- def_delegators :to_range, :eql?, :hash
30
- def_delegators :to_a, :length, :empty?
29
+ ENDS = %i[open unknown].freeze
31
30
 
32
31
  attr_reader :from, :to
33
32
 
34
- def initialize(from = Date.today, to = :open)
35
- self.from, self.to = from, to
33
+ def initialize(from, to)
34
+ @from = coerce_end(from)
35
+ @to = coerce_end(to)
36
+ raise ArgumentError, "reversed interval: #{edtf}" if reversed?
37
+ freeze
36
38
  end
37
39
 
38
- def from=(date)
39
- case date
40
- when Date, :unknown, :open
41
- @from = date
42
- else
43
- throw ArgumentError.new("Intervals cannot start with: #{date}")
44
- end
40
+ # Mixed precisions are not supported;
41
+ # the start's precision takes precedence
42
+ # (the end's if the start has no date).
43
+ def precision
44
+ [from, to].find { |value| value.is_a?(Period) }&.precision
45
45
  end
46
46
 
47
- def to=(date)
48
- case date
49
- when Date, :unknown, :open
50
- @to = date
51
- else
52
- throw ArgumentError.new("Intervals cannot end with: #{date}")
53
- end
47
+ def values
48
+ [from, to]
54
49
  end
55
50
 
56
- [:open, :unknown].each do |method_name|
57
- define_method("#{method_name}_start!") do
58
- @from = method_name
59
- self
60
- end
61
-
62
- define_method("#{method_name}_start?") do
63
- @from == method_name
64
- end
65
-
66
- define_method("#{method_name}_end!") do
67
- @to = method_name
68
- self
69
- end
51
+ def begin
52
+ from.begin unless ENDS.include?(from)
53
+ end
70
54
 
71
- define_method("#{method_name}_end?") do
72
- @to == method_name
73
- end
55
+ def end
56
+ to.end unless ENDS.include?(to)
74
57
  end
75
58
 
76
59
  def open?
77
- open_start? || open_end?
60
+ from == :open || to == :open
78
61
  end
79
62
 
80
63
  def unknown?
81
- unknown_start? || unknown_end?
64
+ from == :unknown || to == :unknown
82
65
  end
83
66
 
84
- # Returns the intervals precision. Mixed precisions are currently not
85
- # supported; in that case, the start date's precision takes precedence.
86
- def precision
87
- min&.precision || max&.precision
88
- end
67
+ def with(**changes)
68
+ return self if changes.empty?
89
69
 
90
- # Returns true if the precisions of start and end date are not the same.
91
- def mixed_precision?
92
- min&.precision != max&.precision
93
- end
70
+ check_keys!(changes, %i[from to])
94
71
 
95
- def each(&block)
96
- step(1, &block)
72
+ self.class.new(changes.fetch(:from, from), changes.fetch(:to, to))
97
73
  end
98
74
 
99
-
100
75
  # call-seq:
101
- # interval.step(by=1) { |date| block } -> self
102
- # interval.step(by=1) -> Enumerator
103
- #
104
- # Iterates over the interval by passing by elements at each step and
105
- # yielding each date to the passed-in block. Note that the semantics
106
- # of by are precision dependent: e.g., a value of 2 can mean 2 days,
107
- # 2 months, or 2 years.
76
+ # interval.each { |period| block } -> self
77
+ # interval.each -> Enumerator
108
78
  #
109
- # If not block is given, returns an enumerator instead.
110
- #
111
- def step(by = 1)
112
- raise ArgumentError unless by.respond_to?(:to_i)
113
-
114
- if block_given?
115
- f, t, by = min, max, by.to_i
116
-
117
- unless f.nil? || t.nil? || by < 1
118
- by = { Date::PRECISIONS[precision] => by }
119
-
120
- until f > t do
121
- yield f
122
- f = f.advance(by)
123
- end
124
- end
79
+ # Iterates over the interval by the start's precision,
80
+ # yielding each unit that begins within the interval,
81
+ # without the qualifiers of the start:
82
+ # 1980-08?/1994 yields the months from 1980-08 to 1994-12.
83
+ # Like endless ranges,
84
+ # intervals with an open or unknown end iterate endlessly;
85
+ # those without a dated start raise a RangeError.
86
+ def each
87
+ return to_enum(:each) unless block_given?
88
+ if ENDS.include?(from)
89
+ raise RangeError, "cannot iterate the interval #{edtf} without a start"
90
+ end
125
91
 
126
- self
127
- else
128
- enum_for(:step, by)
92
+ unit = unqualified(from)
93
+ while within?(unit)
94
+ yield unit
95
+ unit = unit.succ
129
96
  end
97
+ self
130
98
  end
131
99
 
100
+ def to_a
101
+ if endless?
102
+ raise RangeError,
103
+ "cannot convert the endless interval #{edtf} to an array"
104
+ end
132
105
 
133
- # This method always returns false for Range compatibility. EDTF intervals
134
- # always include the last date.
135
- def exclude_end?
136
- false
106
+ super
137
107
  end
138
108
 
109
+ alias entries to_a
139
110
 
140
- # TODO how to handle +/- Infinity for Dates?
141
- # TODO we can't delegate to Ruby range for mixed precision intervals
142
-
143
- # Returns the Interval as a Range.
144
- def to_range
145
- case
146
- when open?, unknown?
147
- nil
148
- else
149
- Range.new(unknown_start? ? Date.new : @from, max)
150
- end
111
+ # Like Range#count, endless intervals count infinitely many units.
112
+ def count(*args, &block)
113
+ args.empty? && block.nil? && endless? ? Float::INFINITY : super
151
114
  end
152
115
 
153
- # Returns true if other is an element of the Interval, false otherwise.
154
- # Comparision is done according to the Interval's min/max date and
155
- # precision.
116
+ # Returns true if other is one of the units the interval yields,
117
+ # like Range#include?, but without iterating:
118
+ # covered and of the interval's precision.
156
119
  def include?(other)
157
- cover?(other) && precision == other.precision
120
+ cover?(other) && Period.precision(other) == precision
158
121
  end
159
- alias member? include?
160
122
 
161
- # Returns true if other is an element of the Interval, false otherwise.
162
- # In contrast to #include? and #member? this method does not take into
163
- # account the date's precision.
164
- def cover?(other)
165
- return false unless other.is_a?(Date)
166
-
167
- other = other.day_precision
168
-
169
- (unbounded_start? || min.day_precision! <= other) &&
170
- (unbounded_end? || other <= max.day_precision!)
123
+ def edtf
124
+ [from, to].map { |value|
125
+ case value
126
+ when :open
127
+ '..'
128
+ when :unknown
129
+ ''
130
+ else
131
+ value.edtf
132
+ end
133
+ }.join('/')
171
134
  end
172
135
 
173
- # call-seq:
174
- # interval.first -> Date or nil
175
- # interval.first(n) -> Array
176
- #
177
- # Returns the first date in the interval, or the first n dates.
178
- def first(n = 1)
179
- if n > 1
180
- (ds = Array(min)).empty? ? ds : ds.concat(ds[0].next(n - 1))
181
- else
182
- min
183
- end
184
- end
136
+ protected
185
137
 
186
- # call-seq:
187
- # interval.last -> Date or nil
188
- # interval.last(n) -> Array
189
- #
190
- # Returns the last date in the interval, or the last n dates.
191
- def last(n = 1)
192
- if n > 1
193
- (ds = Array(max)).empty? ? ds : ds.concat(ds[0].prev(n - 1))
194
- else
195
- max
196
- end
138
+ def state
139
+ [from, to]
197
140
  end
198
141
 
199
- # call-seq:
200
- # interval.min -> Date or nil
201
- # interval.min { |a,b| block } -> Date or nil
202
- #
203
- # Returns the minimum value in the interval. If a block is given, it is
204
- # used to compare values (slower). Returns nil if the first date of the
205
- # interval is larger than the last or if the interval has an unknown or
206
- # open start.
207
- def min(&block)
208
- if block_given?
209
- to_a.min(&block)
210
- else
211
- case
212
- when open_start?, unknown_start?, !(open_end? || unknown_end?) && !open? && to < from
213
- nil
214
- when from.day_precision?
215
- from
216
- when from.month_precision?
217
- from.beginning_of_month
218
- else
219
- from.beginning_of_year
220
- end
221
- end
222
- end
142
+ private
223
143
 
224
- def begin
225
- min
226
- end
144
+ # The end lies before the start (ISO 8601-2 Annex C.1.3.3).
145
+ # Two times compare by instant, so T10:00/T09:00 on one day is reversed.
146
+ def reversed?
147
+ return false if ENDS.include?(from) || ENDS.include?(to)
148
+ return self.end < self.begin unless from.is_a?(::Time) && to.is_a?(::Time)
227
149
 
228
- # call-seq:
229
- # interval.max -> Date or nil
230
- # interval.max { |a,b| block } -> Date or nil
231
- #
232
- # Returns the maximum value in the interval. If a block is given, it is
233
- # used to compare values (slower). Returns nil if the first date of the
234
- # interval is larger than the last or if the interval has an unknown or
235
- # open end.
236
- #
237
- # To calculate the dates, precision is taken into account. Thus, the max
238
- # Date of "2007/2008" would be 2008-12-31, whilst the max Date of
239
- # "2007-12/2008-10" would be 2009-10-31.
240
- def max(&block)
241
- if block_given?
242
- to_a.max(&block)
243
- else
244
- case
245
- when open_end?, unknown_end?, !(open_start? || unknown_start?) && to < from
246
- nil
247
- when to.day_precision?
248
- to
249
- when to.month_precision?
250
- to.end_of_month
251
- else
252
- to.end_of_year
253
- end
254
- end
150
+ span = DateTime.span(to)
151
+ span.zero? ? to.to_r < from.to_r : to.to_r + span <= from.to_r
255
152
  end
256
153
 
257
- def end
258
- max
154
+ def endless?
155
+ ENDS.include?(to)
259
156
  end
260
157
 
261
- # Intervals are compared by their min and max dates. Open and unknown
262
- # starts and ends are treated like -/+ infinity, with open being the
263
- # more extreme of the two. Dates are equal to an interval if they are
264
- # covered by it.
265
- def <=>(other)
266
- case other
267
- when Interval, Season, Epoch
268
- bounds <=> bounds_of(other)
269
- when Date
270
- case
271
- when cover?(other) then 0
272
- when unbounded_start? then -1
273
- else min.day_precision <=> other.day_precision
274
- end
158
+ def within?(unit)
159
+ case to
160
+ when *ENDS
161
+ true
162
+ when ::Time
163
+ unit <= to
275
164
  else
276
- nil
165
+ unit.begin <= self.end
277
166
  end
278
167
  end
279
168
 
280
- def ===(other)
281
- case other
282
- when Interval
283
- (other.unbounded_start? ? unbounded_start? : cover?(other.min)) &&
284
- (other.unbounded_end? ? unbounded_end? : cover?(other.max))
285
- when Date
286
- cover?(other)
169
+ def unqualified(period)
170
+ case period
171
+ when Date, Season
172
+ period.with(uncertain: nil, approximate: nil)
173
+ when Epoch
174
+ period.with(uncertain: false, approximate: false)
287
175
  else
288
- false
176
+ period
289
177
  end
290
178
  end
291
179
 
292
-
293
- # Returns the Interval as an EDTF string.
294
- def edtf
180
+ # Open starts sort before unknown ones, unknown ends before open ones.
181
+ def keys
295
182
  [
296
- from.send(from.respond_to?(:edtf) ? :edtf : :to_s),
297
- to.send(to.respond_to?(:edtf) ? :edtf : :to_s)
298
- ] * '/'
299
- end
300
-
301
- alias to_s edtf
302
-
303
- protected
304
-
305
- def unbounded_start?
306
- open_start? || unknown_start?
307
- end
308
-
309
- def unbounded_end?
310
- open_end? || unknown_end?
311
- end
312
-
313
- START_RANK = { :open => -2, :unknown => -1 }.freeze
314
- END_RANK = { :unknown => 1, :open => 2 }.freeze
315
-
316
- def bounds
317
- [
318
- unbounded_start? ? START_RANK[from] : 0, min,
319
- unbounded_end? ? END_RANK[to] : 0, max
183
+ { open: [-2], unknown: [-1] }.fetch(from) { [0, self.begin] },
184
+ { unknown: [1], open: [2] }.fetch(to) { [0, self.end] },
185
+ rank
320
186
  ]
321
187
  end
322
188
 
323
- private
324
-
325
- def bounds_of(other)
326
- other.is_a?(Interval) ? other.bounds : [0, other.min, 0, other.max]
189
+ def coerce_end(value)
190
+ case value
191
+ when *ENDS, Period
192
+ value
193
+ when ::Date
194
+ EDTF(value)
195
+ else
196
+ raise ArgumentError, "invalid interval end: #{value.inspect}"
197
+ end
327
198
  end
328
-
329
199
  end
330
200
 
331
201
  end