Centralize daypart key canonicalization
This commit is contained in:
@@ -2,7 +2,9 @@ package forecast
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/timeutil"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/weatherdata"
|
||||
@@ -14,6 +16,25 @@ type DaypartDefinition struct {
|
||||
End string `json:"end"`
|
||||
}
|
||||
|
||||
// CanonicalDaypartKey returns the stable identity for a configured daypart name.
|
||||
func CanonicalDaypartKey(value string) string {
|
||||
lower := strings.ToLower(strings.TrimSpace(value))
|
||||
var out strings.Builder
|
||||
lastUnderscore := false
|
||||
for _, r := range lower {
|
||||
if unicode.IsLetter(r) || unicode.IsDigit(r) {
|
||||
out.WriteRune(r)
|
||||
lastUnderscore = false
|
||||
continue
|
||||
}
|
||||
if !lastUnderscore {
|
||||
out.WriteByte('_')
|
||||
lastUnderscore = true
|
||||
}
|
||||
}
|
||||
return strings.Trim(out.String(), "_")
|
||||
}
|
||||
|
||||
type DaypartWindow struct {
|
||||
Name string `json:"name"`
|
||||
Start time.Time `json:"start"`
|
||||
|
||||
@@ -658,3 +658,26 @@ func assertTimedValueClose(t *testing.T, name string, got *TimedValue, want floa
|
||||
t.Fatalf("%s = %#v, want %v", name, got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCanonicalDaypartKey(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
value string
|
||||
want string
|
||||
}{
|
||||
{name: "blank", value: " \t ", want: ""},
|
||||
{name: "casing", value: "MORNING", want: "morning"},
|
||||
{name: "punctuation runs", value: " Morning--Commute / School ", want: "morning_commute_school"},
|
||||
{name: "Unicode", value: "Déjà Vu", want: "déjà_vu"},
|
||||
{name: "letters and digits", value: "Day 1 Outlook", want: "day_1_outlook"},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := CanonicalDaypartKey(tt.value); got != tt.want {
|
||||
t.Fatalf("CanonicalDaypartKey(%q) = %q, want %q", tt.value, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
if CanonicalDaypartKey("Morning commute") != CanonicalDaypartKey("MORNING--COMMUTE") {
|
||||
t.Fatal("equivalent configured names must have the same canonical daypart key")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user