Skip to content

Commit

Permalink
Cache length and added docstrings.
Browse files Browse the repository at this point in the history
  • Loading branch information
rofinn committed Jul 2, 2019
1 parent 60e1495 commit be73c83
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 10 deletions.
50 changes: 41 additions & 9 deletions src/IterTools.jl
Original file line number Diff line number Diff line change
Expand Up @@ -911,19 +911,27 @@ eltype(::Type{TakeWhile{I}}) where {I} = eltype(I)
IteratorEltype(::Type{TakeWhile{I}}) where {I} = IteratorEltype(I)

struct Properties{T}
names
x::T
end

struct PropertyValues{T}
n::Int
names
x::T
end

length(p::Union{Properties, PropertyValues}) = length(p.names)
IteratorSize(::Type{<:Union{Properties, PropertyValues}}) = HasLength()
"""
properties(x)
properties(x::T) where {T} = Properties{T}(propertynames(x), x)
Iterate through the names and value of the properties of `x`.
```jldoctest
julia> collect(properties(1 + 2im))
2-element Array{Any,1}:
(:re, 1)
(:im, 2)
```
"""
function properties(x::T) where T
names = propertynames(x)
return Properties{T}(x, length(names), names)
end

function iterate(p::Properties, state=1)
state > length(p) && return nothing
Expand All @@ -932,7 +940,28 @@ function iterate(p::Properties, state=1)
return ((name, getproperty(p.x, name)), state + 1)
end

propertyvalues(x::T) where {T} = PropertyValues{T}(propertynames(x), x)
struct PropertyValues{T}
x::T
n::Int
names
end

"""
propertynames(x)
Iterate through the values of the properties of `x`.
```jldoctest
julia> collect(propertyvalues(1 + 2im))
2-element Array{Any,1}:
1
2
```
"""
function propertyvalues(x::T) where T
names = propertynames(x)
return PropertyValues{T}(x, length(names), names)
end

function iterate(p::PropertyValues, state=1)
state > length(p) && return nothing
Expand All @@ -941,4 +970,7 @@ function iterate(p::PropertyValues, state=1)
return (getproperty(p.x, name), state + 1)
end

length(p::Union{Properties, PropertyValues}) = p.n
IteratorSize(::Type{<:Union{Properties, PropertyValues}}) = HasLength()

end # module IterTools
2 changes: 1 addition & 1 deletion test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -451,7 +451,7 @@ include("testing_macros.jl")
@test collect(pv2) == collect(tp)
end

# HasLength used as an example no-field struct
# HasLength used as an example no-field struct
pv3 = propertyvalues(HasLength())
@test collect(pv3) == Any[]
end
Expand Down

0 comments on commit be73c83

Please sign in to comment.