Skip to content

Commit

Permalink
Add NamedTuple converters
Browse files Browse the repository at this point in the history
  • Loading branch information
CiaranOMara committed Jun 29, 2021
1 parent 31b6806 commit 1e836aa
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 0 deletions.
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
```
15 changes: 15 additions & 0 deletions src/record.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand Down
24 changes: 24 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 1e836aa

Please sign in to comment.