Skip to content

Commit

Permalink
do not drop repeat keys in Accumulate(::Pairs...) (#861)
Browse files Browse the repository at this point in the history
  • Loading branch information
Krastanov authored Jul 19, 2023
1 parent e3fa7b6 commit ca157a1
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
8 changes: 7 additions & 1 deletion src/accumulator.jl
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,13 @@ end

Accumulator{T, V}() where {T, V} = Accumulator{T, V}(Dict{T, V}())
Accumulator(map::AbstractDict) = Accumulator(Dict(map))
Accumulator(ps::Pair...) = Accumulator(Dict(ps))
function Accumulator(p::Pair, ps::Pair...)
a = Accumulator(Dict(p))
for (k,v) in ps
inc!(a, k, v)
end
a
end

counter(T::Type) = Accumulator{T, Int}()
counter(dct::AbstractDict{T, V}) where {T, V<:Integer} = Accumulator{T, V}(Dict(dct))
Expand Down
11 changes: 10 additions & 1 deletion test/test_accumulator.jl
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@
@test sum(ct) == 6
end

@testset "From Pairs" begin
@testset "From Pairs" begin
acc = Accumulator("a" => 2, "b" => 3, "c" => 1)
@test isa(acc,Accumulator{String,Int})
@test haskey(acc,"a")
Expand All @@ -62,6 +62,15 @@
@test acc["c"] == 1
end

@testset "From Pairs with repeats" begin
acc = Accumulator("a" => 2, "b" => 3, "b" => 1)
@test isa(acc,Accumulator{String,Int})
@test haskey(acc,"a")
@test haskey(acc,"b")
@test acc["a"] == 2
@test acc["b"] == 4
end

@testset "From Vector" begin
ct2 = counter(["a", "a", "b", "b", "a", "c", "c"])
@test isa(ct2, Accumulator{String,Int})
Expand Down

0 comments on commit ca157a1

Please sign in to comment.