Skip to content

Commit

Permalink
feat: adding HasKey
Browse files Browse the repository at this point in the history
  • Loading branch information
samber committed Jun 28, 2024
1 parent 9f52970 commit 5585cbb
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 0 deletions.
13 changes: 13 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,18 @@ 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
```

### Values

Creates an array of the map values.
Expand Down
6 changes: 6 additions & 0 deletions map.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ func Keys[K comparable, V any](in map[K]V) []K {
return result
}

// HasKey returns whether the given key exists.
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 5585cbb

Please sign in to comment.