Skip to content

Commit

Permalink
output unique keys
Browse files Browse the repository at this point in the history
  • Loading branch information
shivamrazorpay committed Jul 20, 2024
1 parent cadc6ea commit c662470
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 5 deletions.
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1038,14 +1038,18 @@ result = lo.Splice([]string{"a", "b"}, 42, "1", "2")

### Keys

Creates an array of the map keys.
Creates an array of the unique map keys.
(Note: The order of the keys is not guaranteed to be the same as the order returned by the map, so can sort them if needed.)

```go
keys := lo.Keys(map[string]int{"foo": 1, "bar": 2})
// []string{"foo", "bar"}

keys := lo.Keys(map[string]int{"foo": 1, "bar": 2}, map[string]int{"baz": 3})
// []string{"foo", "bar", "baz"}

keys := lo.Keys(map[string]int{"foo": 1, "bar": 2}, map[string]int{"bar": 3})
// []string{"foo", "bar"}
```

[[play](https://go.dev/play/p/Uu11fHASqrU)]
Expand Down
8 changes: 7 additions & 1 deletion map.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,18 @@ package lo
// Keys creates an array of the map keys.
// Play: https://go.dev/play/p/Uu11fHASqrU
func Keys[K comparable, V any](in ...map[K]V) []K {
seen := make(map[K]bool)
result := make([]K, 0)

for i := range in {
for k := range in[i] {
result = append(result, k)
if _, exists := seen[k]; !exists {
seen[k] = true
result = append(result, k)
}
}
}

return result
}

Expand Down
6 changes: 3 additions & 3 deletions map_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,12 @@ func TestKeys(t *testing.T) {
sort.Strings(r3)
is.Equal(r3, []string{"bar", "baz", "foo"})

r4 := Keys[int, int]()
is.Equal(r4, []int{})
r4 := Keys[string, int]()
is.Equal(r4, []string{})

r5 := Keys(map[string]int{"foo": 1, "bar": 2}, map[string]int{"bar": 3})
sort.Strings(r5)
is.Equal(r5, []string{"bar", "bar", "foo"})
is.Equal(r5, []string{"bar", "foo"})
}

func TestHasKey(t *testing.T) {
Expand Down

0 comments on commit c662470

Please sign in to comment.