Skip to content

Commit

Permalink
Improve NamedTuple converters
Browse files Browse the repository at this point in the history
  • Loading branch information
CiaranOMara committed May 4, 2024
1 parent 5d3ca48 commit ad7d0e7
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 16 deletions.
10 changes: 8 additions & 2 deletions src/record.jl
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,14 @@ end

Base.convert(::Type{NamedTuple}, record::Record) = convert(NamedTuple{(:chrom, :first, :last, :value)}, record)

function Base.convert(::Type{Record}, nt::NamedTuple{(:chrom, :first, :last, :value)})
return Record(nt.chrom, nt.first, nt.last, nt.value)
function Base.convert(::Type{T}, nt::NamedTuple{(:chrom, :first, :last, :value),Tuple{String,Int64,Int64,R}}) where {R <: Real, T<: Bedgraph.Record}
@debug "Convert - strictly named tuples."
return T(nt.chrom, nt.first, nt.last, nt.value)
end

function Base.convert(::Type{T}, nt::NamedTuple{names,Tuple{String,Int64,Int64,R}}) where {R <: Real, names, T<: Bedgraph.Record}
@debug "Convert - loosely named tuples."
return T(nt[1], nt[2], nt[3], nt[4])
end

function Base.convert(::Type{Record}, str::AbstractString)
Expand Down
34 changes: 20 additions & 14 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -287,26 +287,32 @@ end #testset Internal Helpers

@testset "NamedTuple" begin

record = Record(Bag.line1)
# Check strictly named fields.

nt = (
chrom = Bag.chroms[1],
first = Bag.firsts[1],
last = Bag.lasts[1],
value = Bag.values[1],
nt_strict_names = (
chrom = Bag.record1.chrom,
first=Bag.record1.first,
last=Bag.record1.last,
value=Bag.record1.value
)

@test record == Record(nt)
@test convert(NamedTuple{(:chrom, :first, :last, :value)}, Bag.record1) == convert(NamedTuple, Bag.record1) == nt_strict_names
@test Bag.record1 == convert(Record, nt_strict_names)
@test Bag.record1 == Record(nt_strict_names)

@test convert(NamedTuple{(:chrom, :first, :last, :value)}, record) == convert(NamedTuple, record) == nt
# Check loosely named fields.

# Check renaming of fields.
@test convert(NamedTuple{(:chrom, :left, :right, :value)}, record) == (
chrom = Bag.chroms[1],
left = Bag.firsts[1],
right = Bag.lasts[1],
value = Bag.values[1],
nt_loose_names = (
chrom = Bag.record1.chrom,
left=Bag.record1.first,
right=Bag.record1.last,
value=Bag.record1.value
)

@test convert(NamedTuple{(:chrom, :left, :right, :value)}, Bag.record1) == nt_loose_names
@test Bag.record1 == convert(Record, nt_loose_names)
@test Bag.record1 == Record(nt_loose_names)

end

end # total testset

0 comments on commit ad7d0e7

Please sign in to comment.