Skip to content

Commit

Permalink
feat: adding HasKey (#477)
Browse files Browse the repository at this point in the history
* feat: adding HasKey
  • Loading branch information
samber authored Jun 28, 2024
1 parent 7cce15b commit 33853f5
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ Supported helpers for slices:
Supported helpers for maps:

- [Keys](#keys)
- [HasKey](#HasKey)
- [ValueOr](#valueor)
- [Values](#values)
- [PickBy](#pickby)
Expand Down Expand Up @@ -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.
Expand Down
7 changes: 7 additions & 0 deletions map.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
11 changes: 11 additions & 0 deletions map_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 33853f5

Please sign in to comment.