Skip to content

Commit

Permalink
Add intersect(::AbstractRange, ::AbstractRange)
Browse files Browse the repository at this point in the history
  • Loading branch information
barucden committed Aug 4, 2021
1 parent 5262f3f commit 8c2c523
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
7 changes: 7 additions & 0 deletions base/range.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1143,6 +1143,13 @@ function intersect(r::StepRange, s::StepRange)
step(r) < zero(step(r)) ? StepRange{T,S}(n, -a, m) : StepRange{T,S}(m, a, n)
end

function intersect(r1::AbstractRange, r2::AbstractRange)
if length(r2) < length(r1)
r1, r2 = r2, r1
end
return [x for x in r1 if x r2]
end

function intersect(r1::AbstractRange, r2::AbstractRange, r3::AbstractRange, r::AbstractRange...)
i = intersect(intersect(r1, r2), r3)
for t in r
Expand Down
13 changes: 13 additions & 0 deletions test/ranges.jl
Original file line number Diff line number Diff line change
Expand Up @@ -412,6 +412,19 @@ end
@test intersect(start-Day(10):Day(1):stop-Day(10), start:Day(5):stop) ==
start:Day(5):stop-Day(10)-mod(stop-start, Day(5))
end

@testset "Two AbstractRanges" begin
struct DummyRange{T} <: AbstractRange{T}
r::UnitRange{T}
end
Base.iterate(dr::DummyRange) = iterate(dr.r)
Base.iterate(dr::DummyRange, state) = iterate(dr.r, state)
Base.length(dr::DummyRange) = length(dr.r)
Base.in(x::Int, dr::DummyRange) = in(x, dr.r)
r1 = DummyRange(1:5)
r2 = DummyRange(3:6)
@test intersect(r1, r2) === [3, 4, 5]
end
end
@testset "issubset" begin
@test issubset(1:3, 1:typemax(Int)) #32461
Expand Down

0 comments on commit 8c2c523

Please sign in to comment.