diff --git a/README.md b/README.md index 24668ce..883d0bb 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/map.go b/map.go index 92c77d8..a9eb1c9 100644 --- a/map.go +++ b/map.go @@ -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)) @@ -69,4 +80,4 @@ func MapValues[K comparable, V any, R any](in map[K]V, iteratee func(V, K) R) ma } return result -} \ No newline at end of file +} diff --git a/map_test.go b/map_test.go index f2dcec2..2f42412 100644 --- a/map_test.go +++ b/map_test.go @@ -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)