Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support appending arbitrary container #57

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions src/Table.jl
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,35 @@ function Base.append!(t::Table{<:NamedTuple{names}}, t2::Table{<:NamedTuple{name
return t
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(string("Cannot handle non-table type ", typeof(t2))))
end

function Base.popfirst!(t::Table)
return map(popfirst!, columns(t))
end
Expand Down
15 changes: 15 additions & 0 deletions test/Table.jl
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,21 @@
@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 "append! error handling" begin
@test_throws(
ArgumentError("Cannot handle non-table type Nothing"),
append!(Table(a = [1], b = [2]), nothing)
)
end

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