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 e1cc764
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 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,26 @@ 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)

selfEnd = self.end
selfBegin = self.begin
selfExclude = exclude_end?
otherBegin = other.begin
otherEnd = other.end
otherExclude = other.exclude_end?

!!(__overlap(otherBegin, selfEnd, selfExclude) &&
__overlap(selfBegin, otherEnd, otherExclude) &&
__overlap(selfBegin, selfEnd, selfExclude) &&
__overlap(otherBegin, otherEnd, otherExclude))
end

private def __overlap(from, to, excl)
less = (from || -Float::INFINITY) <=> (to || Float::INFINITY)
less = +1 if less == 0 && excl
less && less <= 0
end
end

0 comments on commit e1cc764

Please sign in to comment.