Skip to content

Commit

Permalink
Support appending arbitrary table
Browse files Browse the repository at this point in the history
  • Loading branch information
tkf committed Dec 15, 2019
1 parent fc1247a commit aea050a
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/Table.jl
Original file line number Diff line number Diff line change
Expand Up @@ -196,9 +196,38 @@ end

function Base.append!(t::Table{<:NamedTuple{names}}, t2::Table{<:NamedTuple{names}}) where {names}
map(append!, columns(t), columns(t2))
return append_columnaccess!(t, t2)
end

_asnamedtuple(T) = data -> _asnamedtuple(T, data)
function _asnamedtuple(::Type{T}, data) where {names, T<:NamedTuple{names}}
if data isa NamedTuple
return T(data)
else
return T(Tuple(getproperty(data, n) for n in names))
end
end

function append_columnaccess!(t::Table, t2)
cols = _asnamedtuple(NamedTuple{columnnames(t)}, columns(t2))
map(append!, columns(t), cols)
return t
end

append_rowaccess!(t::Table, t2) =
mapfoldl(_asnamedtuple(NamedTuple{columnnames(t)}), push!, Tables.rows(t2); init = t)

function Base.append!(t::Table, t2)
if Tables.istable(t2)
if Tables.columnaccess(t2)
return append_columnaccess!(t, t2)
elseif Tables.rowaccess(t2)
return append_rowaccess!(t, t2)
end
end
throw(ArgumentError("Cannot handle non-table type ", typeof(t2)))
end

function Base.popfirst!(t::Table)
return map(popfirst!, columns(t))
end
Expand Down
8 changes: 8 additions & 0 deletions test/Table.jl
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,14 @@
@test isequal(Table(t |> rowtable), t)
end

@testset "append!(_, ::$(typeof(t2)))" for t2 in Any[
[(a=3, b=4)],
(a=[3], b=[4]),
]
t = Table(a=[1], b=[2])
@test append!(t, t2) == Table(a = [1, 3], b = [2, 4])
end

@testset "group" begin
t = Table(a = [1,2,1], b = [2.0, 4.0, 6.0])
out = group(getproperty(:a), t)
Expand Down

0 comments on commit aea050a

Please sign in to comment.