From 8e039c63d3fec035fecd4245d8a0babf87c734bb Mon Sep 17 00:00:00 2001 From: Martin Hebnes Pedersen Date: Fri, 22 Sep 2023 20:14:24 +0200 Subject: [PATCH] catalog: Improve position report's Course * Add func NewCourse() ("constructor") * Code cleanup * Tests --- catalog/position_report.go | 17 +++++++++++++++-- catalog/position_report_test.go | 34 +++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 2 deletions(-) diff --git a/catalog/position_report.go b/catalog/position_report.go index 8633ca5..401667a 100644 --- a/catalog/position_report.go +++ b/catalog/position_report.go @@ -7,6 +7,7 @@ package catalog import ( "bytes" + "errors" "fmt" "math" "time" @@ -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[:])) } } diff --git a/catalog/position_report_test.go b/catalog/position_report_test.go index be33388..559aedc 100644 --- a/catalog/position_report_test.go +++ b/catalog/position_report_test.go @@ -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