Skip to content

Commit

Permalink
catalog: Improve position report's Course
Browse files Browse the repository at this point in the history
* Add func NewCourse() ("constructor")
* Code cleanup
* Tests
  • Loading branch information
martinhpedersen committed Sep 22, 2023
1 parent 6232475 commit 8e039c6
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 2 deletions.
17 changes: 15 additions & 2 deletions catalog/position_report.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ package catalog

import (
"bytes"
"errors"
"fmt"
"math"
"time"
Expand All @@ -27,11 +28,23 @@ type Course struct {
Magnetic bool
}

func NewCourse(degrees int, magnetic bool) (*Course, error) {
if degrees < 0 || degrees > 360 {
return nil, errors.New("degrees out of bounds [0,360]")
}
if degrees == 360 {
degrees = 0
}
c := Course{Magnetic: magnetic}
copy(c.Digits[:], []byte(fmt.Sprintf("%3d", degrees)))
return &c, nil
}

func (c Course) String() string {
if c.Magnetic {
return fmt.Sprintf("%sM", string(c.Digits[:3]))
return fmt.Sprintf("%sM", string(c.Digits[:]))
} else {
return fmt.Sprintf("%sT", string(c.Digits[:3]))
return fmt.Sprintf("%sT", string(c.Digits[:]))
}
}

Expand Down
34 changes: 34 additions & 0 deletions catalog/position_report_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,40 @@ func TestDecToDM(t *testing.T) {
}
}

func omitErr(v *Course, _ error) *Course { return v }

func TestCourseStringer2(t *testing.T) {
// omitErr := func(c *Course, err error) *Course { return c }
tests := map[string]*Course{
"123T": omitErr(NewCourse(123, false)),
"123M": omitErr(NewCourse(123, true)),
}
for expect, in := range tests {
t.Run(expect, func(t *testing.T) {
if in == nil && expect != "" {
t.Fatal("got unexpected nil")
}
if got := in.String(); got != expect {
t.Errorf("Got %q, expected %q", got, expect)
}
})
}
}

func TestCourseStringer(t *testing.T) {
tests := map[string]Course{
"123T": {Digits: [3]byte{'1', '2', '3'}, Magnetic: false},
"123M": {Digits: [3]byte{'1', '2', '3'}, Magnetic: true},
}
for expect, in := range tests {
t.Run(expect, func(t *testing.T) {
if got := in.String(); got != expect {
t.Errorf("Got %q, expected %q", got, expect)
}
})
}
}

func ExamplePosReport_Message() {
lat := 60.18
lon := 5.3972
Expand Down

0 comments on commit 8e039c6

Please sign in to comment.