add GetStateWithDefault helper

state-management
Muhammed Efe Cetin 2025-03-19 12:30:07 +03:00
parent 6fa12bbda8
commit 7f0afef988
No known key found for this signature in database
GPG Key ID: 0AA4D45CBAA86F73
2 changed files with 45 additions and 0 deletions

View File

@ -139,3 +139,13 @@ func MustGetState[T any](s *State, key string) T {
return dep
}
// GetStateWithDefault retrieves a value from the State and casts it to the desired type, returning a default value in case the key is not found.
func GetStateWithDefault[T any](s *State, key string, defaultVal T) T {
dep, ok := GetState[T](s, key)
if !ok {
return defaultVal
}
return dep
}

View File

@ -233,6 +233,23 @@ func Test_MustGetStateGeneric(t *testing.T) {
})
}
func Test_GetStateWithDefault(t *testing.T) {
t.Parallel()
st := newState()
st.Set("flag", true)
flag := GetStateWithDefault[bool](st, "flag", false)
require.True(t, flag)
// mismatched type should return the default value
str := GetStateWithDefault[string](st, "flag", "default")
require.Equal(t, "default", str)
// missing key should return the default value
flag = GetStateWithDefault[bool](st, "missing", false)
require.False(t, flag)
}
func BenchmarkState_Set(b *testing.B) {
b.ReportAllocs()
@ -389,6 +406,24 @@ func BenchmarkState_MustGetStateGeneric(b *testing.B) {
}
}
func BenchmarkState_GetStateWithDefault(b *testing.B) {
b.ReportAllocs()
st := newState()
n := 1000
// pre-populate the state
for i := 0; i < n; i++ {
key := "key" + strconv.Itoa(i)
st.Set(key, i)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
key := "key" + strconv.Itoa(i%n)
GetStateWithDefault[int](st, key, 0)
}
}
func BenchmarkState_Delete(b *testing.B) {
b.ReportAllocs()