Skip to content

Commit

Permalink
optimize formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
tillkuhn committed Dec 10, 2024
1 parent 4214054 commit 08bb051
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 20 deletions.
8 changes: 6 additions & 2 deletions pkg/tracker/report_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,12 @@ func Test_Report(t *testing.T) {
}

func Test_FormatDuration(t *testing.T) {
assert.Equal(t, "-59m", FDur(-59*time.Minute))
assert.Equal(t, "2h", FDur(2*time.Hour))
assert.Equal(t, "-2h", FDur(-2*time.Hour))
assert.Equal(t, "2h5m", FDur(2*time.Hour+5*time.Minute))
assert.Equal(t, "0h5m", FDur(5*time.Minute))
assert.Equal(t, "0h", FDur(0*time.Minute))
assert.Equal(t, "5m", FDur(5*time.Minute))
assert.Equal(t, "2h", FDur(2*time.Hour))
assert.Equal(t, "0m", FDur(0*time.Minute))
assert.Equal(t, "-3h7m", FDur(-3*time.Hour+7*time.Minute*-1))
}
36 changes: 18 additions & 18 deletions pkg/tracker/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,25 +11,25 @@ func TruncateDay(t time.Time) time.Time {
return t.Truncate(hoursPerDay * time.Hour).UTC()
}

// FDur formats a duration to a human-readable string with hours (if > 0) and minutes
// FDur formats a duration to a human-readable string with hours and minutes
// it takes a duration (time.Duration) as input and returns a string representation of it in the format "XhYm",
// where X is the number of hours and Y is the number of minutes.
// The function handles edge cases such as zero minutes or negative hours.
func FDur(d time.Duration) string {
minutes := int(d.Minutes()) % minPerHour
if d.Hours() < 0 {
minutes = int(math.Abs(d.Minutes())) % minPerHour // no negative minutes
if d.Minutes() == 0 {
return "0m"
}
if minutes == 0 {
return fmt.Sprintf("%dh", int(d.Hours()))
hourStr := ""
if d.Hours() > 1 || d.Hours() < -1 {
hourStr = fmt.Sprintf("%dh", int(d.Hours()))
}
return fmt.Sprintf("%dh%dm", int(d.Hours()), minutes)
/*
switch {
case d.Hours() > 0:
return fmt.Sprintf("%dh%dm", int(d.Hours()), int(d.Minutes())%minPerHour)
case d.Hours() < 0:
return fmt.Sprintf("%dh%dm", int(d.Hours()), int(math.Abs(d.Minutes()))%minPerHour)
default:
return fmt.Sprintf("%dm", int(d.Minutes()))
}
*/
minStr := ""
if int(d.Minutes())%minPerHour != 0 {
if d.Hours() <= -1 {
minStr = fmt.Sprintf("%dm", int(math.Abs(d.Minutes()))%minPerHour) // no negative minutes in negative hours
} else {
minStr = fmt.Sprintf("%dm", int(d.Minutes())%minPerHour)
}
}
return hourStr + minStr
}

0 comments on commit 08bb051

Please sign in to comment.