Skip to content

Commit

Permalink
Add {first,last}(::AbstractVector, ::Integer) methods
Browse files Browse the repository at this point in the history
  • Loading branch information
giordano committed Feb 25, 2020
1 parent ef0e0f2 commit f54c140
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
42 changes: 42 additions & 0 deletions base/abstractarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,27 @@ function first(itr)
x[1]
end

"""
first(v::AbstractVector, n::Integer)
Get the first n elements of the vector, without going out-of-bounds.
# Examples
```jldoctest
julia> first(["foo", "bar", "qux"], 2)
2-element Array{String,1}:
"foo"
"bar"
julia> first(1:6, 10)
1:6
julia> first(Bool[], 1)
0-element Array{Bool,1}
```
"""
first(v::AbstractVector, n::Integer) = @inbounds v[firstindex(v):min(firstindex(v) - 1 + n, end)]

"""
last(coll)
Expand All @@ -361,6 +382,27 @@ julia> last([1; 2; 3; 4])
"""
last(a) = a[end]

"""
last(v::AbstractVector, n::Integer)
Get the last n elements of the vector, without going out-of-bounds.
# Examples
```jldoctest
julia> last(["foo", "bar", "qux"], 2)
2-element Array{String,1}:
"bar"
"qux"
julia> last(1:6, 10)
1:6
julia> first(Float64[], 1)
0-element Array{Float64,1}
```
"""
last(v::AbstractArray, n::Integer) = @inbounds v[max(firstindex(v), end + 1 - n):end]

"""
strides(A)
Expand Down
12 changes: 12 additions & 0 deletions test/abstractarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -999,3 +999,15 @@ end
@testset "vcat with mixed elements" begin
@test vcat(Nothing[], [missing], [1.0], [Int8(1)]) isa Vector{Union{Missing, Nothing, Float64}}
end

@testset "first/last n elements of vector" begin
v = [1, 13, 42]
@test first(v, -2) == []
@test first(v, 2) == v[1:2]
@test first(v, 100) == v
@test first(v, 1) != v[1]
@test last(v, -2) == []
@test last(v, 2) == v[end-1:end]
@test last(v, 100) == v
@test last(v, 1) != v[end]
end

0 comments on commit f54c140

Please sign in to comment.