multi_range icon indicating copy to clipboard operation
multi_range copied to clipboard

Allow using dates in the ranges

Open frsantos opened this issue 2 years ago • 3 comments

When passed a range of dates, it fails when doing operations:

p1 = Date.new(2023, 10, 1)..Date.new(2023, 12, 1)
p2 = Date.new(2023, 1, 1)..Date.new(2023, 1, 31)

MultiRange.new([p1]) & p2

NoMethodError: undefined method `begin' for Sun, 01 Jan 2023:Date
from /usr/local/bundle/gems/multi_range-2.2.1/lib/multi_range.rb:30:in `each'

I tried transforming the dates into integers, but it is way too slow:

p1 = Date.new(2023, 10, 1)..Date.new(2023, 12, 1)
p2 = Date.new(2023, 1, 1)..Date.new(2023, 1, 31)

r1 = p1.begin.to_time.to_i..p1.end.to_time.to_i
r2 = p2.begin.to_time.to_i..p2.end.to_time.to_i

start = Time.now
MultiRange.new([r1]) & r2
"Time: #{Time.now - start}sec"

=> "Time: 1.395833396sec"

Is there a way of working with dates efficiently?

frsantos avatar Nov 29 '23 13:11 frsantos

Interestingly, the following is fast:

p1 = Date.new(2023, 10, 1)..Date.new(2023, 12, 1)
p2 = Date.new(2023, 1, 1)..Date.new(2023, 1, 31)
r1 = p1.begin.to_time.to_i..p1.end.to_time.to_i
r2 = p2.begin.to_time.to_i..p2.end.to_time.to_i
start = Time.now
MultiRange.new([r1]) & MultiRange.new([r2])
"Time: #{Time.now - start}sec"

=> "Time: 0.000126523sec"

frsantos avatar Nov 29 '23 16:11 frsantos

There seems to have a performance issue in MultiRange.new([r1]) & r2.

https://github.com/khiav223577/multi_range/blob/880aef32acc500f645b35d949ff5bc22cd04a7b1/lib/multi_range.rb#L30

It will treat r2 as an array of ranges, and will try to flatten it, which will become an array with 2592001 elements

r2.size
# => 2592001

khiav223577 avatar Dec 07 '23 02:12 khiav223577

The performance issue was resolved in v2.2.2

khiav223577 avatar Jan 09 '24 04:01 khiav223577