Skip to content

Commit

Permalink
add efficient findfirst method for StepRange (#30778)
Browse files Browse the repository at this point in the history
  • Loading branch information
marekkukan-tw authored and JeffBezanson committed Jan 23, 2019
1 parent 81ef652 commit 91162e9
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
7 changes: 7 additions & 0 deletions base/array.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1741,6 +1741,13 @@ end
findfirst(testf::Function, A::Union{AbstractArray, AbstractString}) =
findnext(testf, A, first(keys(A)))

function findfirst(p::Union{Fix2{typeof(isequal),T},Fix2{typeof(==),T}}, r::StepRange{T,S}) where {T,S}
first(r) <= p.x <= last(r) || return nothing
d = convert(S, p.x - first(r))
iszero(d % step(r)) || return nothing
return d ÷ step(r) + 1
end

"""
findprev(A, i)
Expand Down
6 changes: 6 additions & 0 deletions test/ranges.jl
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,12 @@ end
@test findall(in(span), r) == 1:6
end
end
@testset "findfirst" begin
@test findfirst(isequal(7), 1:2:10) == 4
@test findfirst(==(7), 1:2:10) == 4
@test findfirst(==(10), 1:2:10) == nothing
@test findfirst(==(11), 1:2:10) == nothing
end
@testset "reverse" begin
@test reverse(reverse(1:10)) == 1:10
@test reverse(reverse(typemin(Int):typemax(Int))) == typemin(Int):typemax(Int)
Expand Down

0 comments on commit 91162e9

Please sign in to comment.