From a706d16c5aade88108aac609973bce9641c78284 Mon Sep 17 00:00:00 2001 From: Dan Jones Date: Thu, 7 Sep 2023 11:00:16 -0500 Subject: [PATCH] =?UTF-8?q?=F0=9F=9A=A7=20Add=20utils.HourMinSecToSeconds?= =?UTF-8?q?=20func?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- utils/utils.go | 14 ++++++++++++++ utils/utils_hms_test.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 utils/utils_hms_test.go diff --git a/utils/utils.go b/utils/utils.go index b0d7c0c..663ef23 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -3,6 +3,8 @@ package utils import ( "fmt" p "path" + "strings" + t "time" ) func GetShortPath(path string) string { @@ -11,3 +13,15 @@ func GetShortPath(path string) string { dir = p.Base(dir) return fmt.Sprintf("%s/%s", dir, base) } + +func HourMinSecToSeconds(time string) float64 { + parts := strings.Split(time, ":") + units := []string{"h", "m", "s"} + units = units[len(units)-len(parts):] + f := "" + for idx, part := range parts { + f = f + part + units[idx] + } + dur, _ := t.ParseDuration(f) + return dur.Seconds() +} diff --git a/utils/utils_hms_test.go b/utils/utils_hms_test.go new file mode 100644 index 0000000..dfe9713 --- /dev/null +++ b/utils/utils_hms_test.go @@ -0,0 +1,30 @@ +package utils + +import "testing" + +func hmsTest(t *testing.T, time string, expected float64) { + found := HourMinSecToSeconds(time) + if found != expected { + t.Fatalf(`HourMinSecToSeconds("%s") = %v, want %v`, time, found, expected) + } +} + +func TestJustSeconds(t *testing.T) { + hmsTest(t, "4.23", 4.23) +} + +func TestMinuteSeconds(t *testing.T) { + hmsTest(t, "2:3.45", 123.45) +} + +func TestHourMinuteSeconds(t *testing.T) { + hmsTest(t, "3:5:12.43", 11112.43) +} + +func TestLeadingZeros(t *testing.T) { + hmsTest(t, "03:05:02.43", 11102.43) +} + +func TestWholeSecond(t *testing.T) { + hmsTest(t, "4:2", 242) +}