Skip to content

Commit

Permalink
allow more types in Extrema
Browse files Browse the repository at this point in the history
  • Loading branch information
joshday committed Jan 11, 2019
1 parent e32e0e2 commit bc70137
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
15 changes: 11 additions & 4 deletions src/stats/stats.jl
Original file line number Diff line number Diff line change
Expand Up @@ -361,18 +361,25 @@ Maximum and minimum.
maximum(o)
minimum(o)
"""
# T is type to store data, S is type of single observation.
# E.g. you may want to accept any Number even if you are storing values as Float64
mutable struct Extrema{T,S} <: OnlineStat{S}
min::T
max::T
n::Int
function Extrema(T::Type = Float64)
a, b, S = extrema_init(T)
new{T,S}(a, b, 0)
end
end
Extrema(T::Type{<:Number} = Float64) = Extrema{T,Number}(typemax.(T), typemin.(T), 0)
Extrema(T::Type) = Extrema{T,T}(typemax.(T), typemin.(T), 0)
Extrema(initmin::T, initmax::T) where {T} = Extrema{T}(initmin, initmax, 0)
extrema_init(T::Type{<:Number}) = typemax(T), typemin(T), Number
extrema_init(T::Type{String}) = "", "", String
extrema_init(T::Type{Date}) = typemax(Date), typemin(Date), Date
extrema_init(T::Type) = rand(T), rand(T), T
function _fit!(o::Extrema, y)
(o.n += 1) == 1 && (o.min = o.max = y)
o.min = min(o.min, y)
o.max = max(o.max, y)
o.n += 1
end
function _merge!(o::Extrema, o2::Extrema)
o.min = min(o.min, o2.min)
Expand Down
4 changes: 4 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,10 @@ end
o = fit!(Extrema(Date), Date(2010):Day(1):Date(2011))
@test minimum(o) == Date(2010)
@test maximum(o) == Date(2011)

@test value(fit!(Extrema(Char), 'a':'z')) == ('a', 'z')
@test value(fit!(Extrema(Char), "abc")) == ('a', 'c')
@test value(fit!(Extrema(String), ["a", "b"])) == ("a", "b")
end
#-----------------------------------------------------------------------# Fit[Dist]
@testset "Fit[Dist]" begin
Expand Down

0 comments on commit bc70137

Please sign in to comment.