Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit cfd832f

Browse files
committedFeb 25, 2020
Add {first,last}(::AbstractVector, ::Integer) methods
1 parent ef0e0f2 commit cfd832f

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed
 

‎base/abstractarray.jl

+42
Original file line numberDiff line numberDiff line change
@@ -343,6 +343,27 @@ function first(itr)
343343
x[1]
344344
end
345345

346+
"""
347+
first(v::AbstractVector, n::Integer)
348+
349+
Get the first n elements of the vector, without going out-of-bounds.
350+
351+
# Examples
352+
```jldoctest
353+
julia> first(["foo", "bar", "qux"], 2)
354+
2-element Array{String,1}:
355+
"foo"
356+
"bar"
357+
358+
julia> first(1:6, 10)
359+
1:6
360+
361+
julia> first(Bool[], 1)
362+
0-element Array{Bool,1}
363+
```
364+
"""
365+
first(v::AbstractVector, n::Integer) = @inbounds v[firstindex(v):min(firstindex(v) - 1 + n, end)]
366+
346367
"""
347368
last(coll)
348369
@@ -361,6 +382,27 @@ julia> last([1; 2; 3; 4])
361382
"""
362383
last(a) = a[end]
363384

385+
"""
386+
last(v::AbstractVector, n::Integer)
387+
388+
Get the last n elements of the vector, without going out-of-bounds.
389+
390+
# Examples
391+
```jldoctest
392+
julia> last(["foo", "bar", "qux"], 2)
393+
2-element Array{String,1}:
394+
"bar"
395+
"qux"
396+
397+
julia> last(1:6, 10)
398+
1:6
399+
400+
julia> first(Float64[], 1)
401+
0-element Array{Float64,1}
402+
```
403+
"""
404+
last(v::AbstractArray, n::Integer) = @inbounds v[max(firstindex(v), end + 1 - n):end]
405+
364406
"""
365407
strides(A)
366408

‎test/abstractarray.jl

+12
Original file line numberDiff line numberDiff line change
@@ -999,3 +999,15 @@ end
999999
@testset "vcat with mixed elements" begin
10001000
@test vcat(Nothing[], [missing], [1.0], [Int8(1)]) isa Vector{Union{Missing, Nothing, Float64}}
10011001
end
1002+
1003+
@testset "first/last n elements of vector" begin
1004+
v = [1, 13, 42]
1005+
@test first(v, -2) == []
1006+
@test first(v, 2) == v[1:2]
1007+
@test first(v, 100) == v
1008+
@test first(v, 1) != v[1]
1009+
@test last(v, -2) == []
1010+
@test last(v, 2) == v[end-1:end]
1011+
@test last(v, 100) == v
1012+
@test last(v, 1) != v[end]
1013+
end

0 commit comments

Comments
 (0)
Please sign in to comment.