diff --git a/README.md b/README.md index 09c4377..44f9a8c 100644 --- a/README.md +++ b/README.md @@ -91,5 +91,19 @@ header = Bedgraph.generate_basic_header("chr19", records[1].first, records[end]. open(output_file, "w") do io write(io, header, records) end +``` + +#### Converting records + +Below are some examples of `Bedgraph.Record` conversions provided by this package. +```julia +using Bedgraph + +record = Record("chr1", 10, 20) + +# Convert record to NamedTuple. +nt = convert(NamedTuple, record) +# Convert record to NamedTuple and rename fields. +nt = convert(NamedTuple{(:chrom, :left, :right, :value)}, record) ``` diff --git a/src/record.jl b/src/record.jl index c5c555f..0bcf8f8 100644 --- a/src/record.jl +++ b/src/record.jl @@ -22,6 +22,21 @@ function Record{T}(data) :: Record{T} where T return data end +function Base.convert(::Type{NamedTuple{names}}, record::Record) where {names} + return NamedTuple{names}(( + record.chrom, + record.first, + record.last, + record.value, + )) +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) +end + function Base.convert(::Type{Record}, str::AbstractString) data = _split_line(str) return Record(data[1], data[2], data[3], data[4]) diff --git a/test/runtests.jl b/test/runtests.jl index e1c5420..169c26d 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -284,4 +284,28 @@ end #testset Conversion end #testset Internal Helpers +@testset "NamedTuple" begin + + record = Record(Bag.line1) + + nt = ( + chrom = Bag.chroms[1], + first = Bag.firsts[1], + last = Bag.lasts[1], + value = Bag.values[1], + ) + + @test record == Record(nt) + + @test convert(NamedTuple{(:chrom, :first, :last, :value)}, record) == convert(NamedTuple, record) == nt + + # 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], + ) +end + end # total testset