add has method

state-management
Muhammed Efe Cetin 2025-03-19 15:20:41 +03:00
parent 8f5aeedc39
commit cbd2f09999
No known key found for this signature in database
GPG Key ID: 0AA4D45CBAA86F73
3 changed files with 48 additions and 0 deletions

View File

@ -130,6 +130,22 @@ if ratio, ok := app.State().GetFloat64("scalingFactor"); ok {
}
```
### Has
Has checks if a key exists in the State.
```go title="Signature"
func (s *State) Has(key string) bool
```
**Usage Example:**
```go
if app.State().Has("appName") {
fmt.Println("App Name is set.")
}
```
### Delete
Delete removes a key-value pair from the State.

View File

@ -84,6 +84,13 @@ func (s *State) GetFloat64(key string) (float64, bool) {
return 0, false
}
// Has checks if a key is present in the State.
// It returns a boolean indicating if the key is present.
func (s *State) Has(key string) bool {
_, ok := s.Get(key)
return ok
}
// Delete removes a key-value pair from the State.
func (s *State) Delete(key string) {
s.dependencies.Delete(key)

View File

@ -120,6 +120,15 @@ func TestState_MustGet(t *testing.T) {
})
}
func TestState_Has(t *testing.T) {
t.Parallel()
st := newState()
st.Set("key", "value")
require.True(t, st.Has("key"))
}
func TestState_Delete(t *testing.T) {
t.Parallel()
st := newState()
@ -424,6 +433,22 @@ func BenchmarkState_GetStateWithDefault(b *testing.B) {
}
}
func BenchmarkState_Has(b *testing.B) {
b.ReportAllocs()
st := newState()
n := 1000
// pre-populate the state
for i := 0; i < n; i++ {
st.Set("key"+strconv.Itoa(i), i)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
st.Has("key" + strconv.Itoa(i%n))
}
}
func BenchmarkState_Delete(b *testing.B) {
b.ReportAllocs()