Skip to content

Commit

Permalink
Implement keys and pairs for Enumerate
Browse files Browse the repository at this point in the history
  • Loading branch information
knuesel committed Jan 17, 2023
1 parent 5f40f15 commit 23c1f45
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
7 changes: 7 additions & 0 deletions base/iterators.jl
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,13 @@ end
(i, n[1]), (i-1, ri, n[2])
end

keys(e::Enumerate) = OneTo(length(e.itr))

# This will work even when keys doesn't (due to length being undefined)
pairs(e::Enumerate) = map(e) do (i, el)
Pair(i, el)
end

"""
pairs(IndexLinear(), A)
pairs(IndexCartesian(), A)
Expand Down
23 changes: 18 additions & 5 deletions test/iterators.jl
Original file line number Diff line number Diff line change
Expand Up @@ -80,12 +80,25 @@ let b = IOBuffer("foo\n")
@test collect(Base.EachLine(b, keep=true, ondone=()->0)) == ["foo\n"]
end

# enumerate (issue #6284)
let b = IOBuffer("1\n2\n3\n"), a = []
for (i,x) in enumerate(eachline(b))
push!(a, (i,x))
@testset "Iterators.enumerate" begin
# issue #6284
let b = IOBuffer("1\n2\n3\n"), a = []
for (i,x) in enumerate(eachline(b))
push!(a, (i,x))
end
@test a == [(1,"1"),(2,"2"),(3,"3")]
end

# keys and pairs
let it = enumerate(zip(1:2, 3:4))
@test collect(keys(it)) == [1, 2]
@test collect(pairs(it)) == [1=>(1,3), 2=>(2,4)]
end

# pairs when length (and hence keys) is undefined
let b = IOBuffer("1\n2\n3\n"), it=enumerate(eachline(b))
@test collect(pairs(it)) == [1=>"1", 2=>"2", 3=>"3"]
end
@test a == [(1,"1"),(2,"2"),(3,"3")]
end

# zip eachline (issue #7369)
Expand Down

0 comments on commit 23c1f45

Please sign in to comment.