Skip to content

Commit

Permalink
Add Range#overlap?
Browse files Browse the repository at this point in the history
  • Loading branch information
headius committed Feb 13, 2025
1 parent ca45fa5 commit 5be999a
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions core/src/main/ruby/jruby/kernel/range.rb
Original file line number Diff line number Diff line change
Expand Up @@ -246,4 +246,30 @@ def self.cond_error(v)
end
end
private_constant :BSearch

def overlap?(other)
raise TypeError, "wrong argument type #{other.class} (expected Range)" unless other.is_a?(Range)

self_begin = self.begin || NEGATIVE_INFINITY
self_end = self.end || INFINITY
self_exclude = exclude_end?
other_begin = other.begin || NEGATIVE_INFINITY
other_end = other.end || INFINITY
other_exclude = other.exclude_end?

!!(__overlap(other_begin, self_end, self_exclude) &&
__overlap(self_begin, other_end, other_exclude) &&
__overlap(self_begin, self_end, self_exclude) &&
__overlap(other_begin, other_end, other_exclude))
end

private def __overlap(from, to, excl)
less = from <=> to
less = +1 if less == 0 && excl
less && less <= 0
end

INFINITY = Float::INFINITY
NEGATIVE_INFINITY = -Float::INFINITY
private_constant :NEGATIVE_INFINITY, :INFINITY
end

0 comments on commit 5be999a

Please sign in to comment.