guava icon indicating copy to clipboard operation
guava copied to clipboard

add Range.overlaps(Range) method

Open bemace opened this issue 10 years ago • 8 comments

Seems very strange that the Range class doesn't have an overlaps(Range) or intersects(Range) method.

I expect it would essentially be

public boolean overlaps(Range other) {
    return isConnected(other) && !intersection(other).isEmpty();
}

bemace avatar Jun 26 '15 18:06 bemace

This is difficult without a DiscreteDomain. Your current implementation would treat [0, 1) and (0, 1] as overlapping, even though there aren't actually any integers in their intersection.

lowasser avatar Jun 26 '15 19:06 lowasser

I see 32 hits in Google code for isConnected[^;{}]*intersection[^;{}]*isEmpty (PCRE:yes, exclude com/google/common/collect). I wonder if these are worth a look, either as evidence for the usefulness of the method or evidence that the approach is bug-prone.

cpovirk avatar Jun 26 '15 20:06 cpovirk

I've made this call several times in my own code when dealing with ranges. Ranges that are part of a DiscreteDomain deserve special consideration. As this method is mostly a convenience to save code and increase readability, perhaps two versions of the method, one for DiscreteDomain Ranges, and one for non-discrete? The method for DiscreteDomain ranges could canonicalize the ranges sent in and the caller would get their expected result. The non-discrete method could do the connected/intersection call as-is. Otherwise, a single method with a clear API documentation would be nice as well. Either way, I think it's a method that would see some use and I would love to see it added.

arustleund avatar Jun 15 '16 14:06 arustleund

Would be very useful! We're using isConnected(other) && !intersection(other).isEmpty() too (for Range<LocalDateTime>)

jwgmeligmeyling avatar Mar 15 '19 12:03 jwgmeligmeyling

FYI This is how PostgreSQL compares ranges

https://github.com/postgres/postgres/blob/a77315fdf2a197a925e670be2d8b376c4ac02efc/src/backend/utils/adt/rangetypes.c#L823-L854

hden avatar Apr 10 '20 05:04 hden

Is there any plan to implement overlap method on Range?

ayushsangani avatar Oct 18 '21 18:10 ayushsangani

so, is it done now? if not, i'm current coming into the same problem and very glad to contribute my implementation @cpovirk

alwinlin23 avatar Mar 11 '22 07:03 alwinlin23