From bb23251ffc0c39524e219a22309005ddb8fc11b1 Mon Sep 17 00:00:00 2001 From: David Banham Date: Fri, 31 Mar 2023 11:01:56 +1100 Subject: [PATCH] Add less than text --- README.md | 1 + main.go | 22 ++++++++++++++++++---- main_test.go | 15 +++++++++++++++ 3 files changed, 34 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 0adb47f..89093ef 100644 --- a/README.md +++ b/README.md @@ -17,6 +17,7 @@ example := time.Hour * 24 + time.Minute * 4 + time.Second * 8 fmt.Println(human_duration.String(example, "second")) // 1 day 4 minutes 8 seconds fmt.Println(human_duration.String(example, "minute")) // 1 day 4 minutes fmt.Println(human_duration.String(example, "day")) // 1 day +fmt.Println(human_duration.String(example, "year")) // less than a year day := time.Hour * 24 year := day * 365 diff --git a/main.go b/main.go index 2a36b1d..865a373 100644 --- a/main.go +++ b/main.go @@ -48,6 +48,11 @@ func StringCeiling(duration time.Duration, precision, ceiling string) string { return StringCeilingPadded(duration, precision, ceiling, false) } +type chunk struct { + singularName string + amount int64 +} + func StringCeilingPadded(duration time.Duration, precision, ceiling string, padded bool) string { years := int64(duration.Hours() / 24 / 365) weeks := int64(math.Mod(float64(int64(duration.Hours()/24/7)), 52)) @@ -81,10 +86,7 @@ func StringCeilingPadded(duration time.Duration, precision, ceiling string, padd years = 0 } - chunks := []struct { - singularName string - amount int64 - }{ + chunks := []chunk{ {"year", years}, {"week", weeks}, {"day", days}, @@ -100,12 +102,20 @@ func StringCeilingPadded(duration time.Duration, precision, ceiling string, padd unpaddedNumberFormat := "%d" paddedNumberFormat := "%02d" + hitSomething := false + var targetChunk chunk + for _, chunk := range chunks { if preciseEnough { continue } + if chunk.amount != 0 { + hitSomething = true + } + if chunk.singularName == precision || chunk.singularName+"s" == precision { + targetChunk = chunk preciseEnough = true } @@ -126,6 +136,10 @@ func StringCeilingPadded(duration time.Duration, precision, ceiling string, padd } } + if !hitSomething { + return "less than a " + targetChunk.singularName + } + return strings.Join(parts, " ") } diff --git a/main_test.go b/main_test.go index 25911f7..19533a8 100644 --- a/main_test.go +++ b/main_test.go @@ -46,6 +46,11 @@ func TestString(t *testing.T) { precision: "day", result: "1 day", }, + { + duration: day + time.Minute*4 + time.Second*8, + precision: "year", + result: "less than a year", + }, { duration: year*4 + day*2, precision: "second", @@ -116,6 +121,16 @@ func TestString(t *testing.T) { precision: "week", result: "2 weeks", }, + { + duration: day, + precision: "week", + result: "less than a week", + }, + { + duration: day + time.Hour, + precision: "week", + result: "less than a week", + }, } for _, fixture := range data {