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 b1db906
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
9 changes: 9 additions & 0 deletions base/range.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1143,6 +1143,15 @@ 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
common = Iterators.filter(x -> x r2, r1)
seen = Set{eltype(vec)}(common)
return vectorfilter(_shrink_filter!(seen), common)
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
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{Int}([1, 2, 3, 3, 4, 5])
r2 = DummyRange{Int}([3, 3, 4, 5, 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 b1db906

Please sign in to comment.