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 f93db10
Show file tree
Hide file tree
Showing 2 changed files with 44 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 @@ -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

0 comments on commit f93db10

Please sign in to comment.