From be73c83a462233aff2c6ca002036c2bf2091e0da Mon Sep 17 00:00:00 2001 From: rofinn Date: Tue, 2 Jul 2019 16:25:44 -0500 Subject: [PATCH] Cache length and added docstrings. --- src/IterTools.jl | 50 +++++++++++++++++++++++++++++++++++++++--------- test/runtests.jl | 2 +- 2 files changed, 42 insertions(+), 10 deletions(-) diff --git a/src/IterTools.jl b/src/IterTools.jl index a0e5feb..6ac503b 100644 --- a/src/IterTools.jl +++ b/src/IterTools.jl @@ -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 @@ -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 @@ -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 diff --git a/test/runtests.jl b/test/runtests.jl index f701aab..3ce8d9a 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -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