mirror of
https://github.com/samber/lo.git
synced 2025-09-26 20:11:13 +08:00
15
README.md
15
README.md
@@ -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
7
map.go
@@ -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 {
|
||||
|
11
map_test.go
11
map_test.go
@@ -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)
|
||||
|
Reference in New Issue
Block a user