exercism/go/nucleotide-count/dna.go

39 lines
848 B
Go
Raw Normal View History

2016-09-03 14:53:54 +00:00
package dna
import (
"errors"
"strings"
)
// Histogram is just a map
type Histogram map[byte]int
// DNAProc is a struct that holds a dna strand
type DNAProc struct {
strand string
}
// DNA is the function that creates DNAProcs
func DNA(st string) *DNAProc {
return &DNAProc{strand: st}
}
// Count takes a nucleotide byte and returns how many there are
// or an error if it's an invalid nucleotide
func (d *DNAProc) Count(n byte) (int, error) {
if n != 'A' && n != 'C' && n != 'G' && n != 'T' {
return 0, errors.New("Invalid Nucleotide " + string(n))
}
return strings.Count(d.strand, string(n)), nil
}
// Counts returns a Histogram of all nucleotide counts
func (d *DNAProc) Counts() Histogram {
h := make(Histogram)
h['A'], _ = d.Count('A')
h['C'], _ = d.Count('C')
h['G'], _ = d.Count('G')
h['T'], _ = d.Count('T')
return h
}