feat: adding HasKey (#477)

* feat: adding HasKey
This commit is contained in:
Samuel Berthe
2024-06-28 21:53:35 +02:00
committed by GitHub
parent 7cce15b3d5
commit 33853f5d82
3 changed files with 33 additions and 0 deletions

View File

@@ -122,6 +122,7 @@ Supported helpers for slices:
Supported helpers for maps:
- [Keys](#keys)
- [HasKey](#HasKey)
- [ValueOr](#valueor)
- [Values](#values)
- [PickBy](#pickby)
@@ -989,6 +990,20 @@ keys := lo.Keys(map[string]int{"foo": 1, "bar": 2})
[[play](https://go.dev/play/p/Uu11fHASqrU)]
### HasKey
Returns whether the given key exists.
```go
exists := lo.HasKey(map[string]int{"foo": 1, "bar": 2}, "foo")
// true
exists := lo.HasKey(map[string]int{"foo": 1, "bar": 2}, "baz")
// false
```
[[play](https://go.dev/play/p/aVwubIvECqS)]
### Values
Creates an array of the map values.

7
map.go
View File

@@ -12,6 +12,13 @@ func Keys[K comparable, V any](in map[K]V) []K {
return result
}
// HasKey returns whether the given key exists.
// Play: https://go.dev/play/p/aVwubIvECqS
func HasKey[K comparable, V any](in map[K]V, key K) bool {
_, ok := in[key]
return ok
}
// Values creates an array of the map values.
// Play: https://go.dev/play/p/nnRTQkzQfF6
func Values[K comparable, V any](in map[K]V) []V {

View File

@@ -19,6 +19,17 @@ func TestKeys(t *testing.T) {
is.Equal(r1, []string{"bar", "foo"})
}
func TestHasKey(t *testing.T) {
t.Parallel()
is := assert.New(t)
r1 := HasKey(map[string]int{"foo": 1}, "bar")
is.False(r1)
r2 := HasKey(map[string]int{"foo": 1}, "foo")
is.True(r2)
}
func TestValues(t *testing.T) {
t.Parallel()
is := assert.New(t)