Added ValuesF helper

This commit is contained in:
Anatoly Ibragimov
2022-03-22 17:02:11 +03:00
parent 62b3831d15
commit 279689f73f
3 changed files with 30 additions and 1 deletions

View File

@@ -540,6 +540,15 @@ values := lo.Values[string, int](map[string]int{"foo": 1, "bar": 2})
// []int{1, 2}
```
### ValuesF
same as Values, but additionally filters map elements by provided keys.
```go
valuesF := ValuesF[string, int](map[string]int{"foo": 1, "bar": 2, "baz": 3}, []string{"foo", "baz"})
// []int{1, 3}
```
### Entries
Transforms a map into array of key/value pairs.

11
map.go
View File

@@ -22,6 +22,17 @@ func Values[K comparable, V any](in map[K]V) []V {
return result
}
// ValuesF same as Values, but additionally filters map elements by provided keys.
func ValuesF[K comparable, V any](in map[K]V, keys []K) []V {
r := make([]V, 0, len(in))
for k, v := range in {
if Contains(keys, k) {
r = append(r, v)
}
}
return r
}
// Entries transforms a map into array of key/value pairs.
func Entries[K comparable, V any](in map[K]V) []Entry[K, V] {
entries := make([]Entry[K, V], 0, len(in))

View File

@@ -26,6 +26,15 @@ func TestValues(t *testing.T) {
is.Equal(r1, []int{1, 2})
}
func TestValuesF(t *testing.T) {
is := assert.New(t)
r1 := ValuesF[string, int](map[string]int{"foo": 1, "bar": 2, "baz": 3}, []string{"foo", "baz"})
sort.Ints(r1)
is.Equal(r1, []int{1, 3})
}
func TestEntries(t *testing.T) {
is := assert.New(t)