diff --git a/maputil/map.go b/maputil/map.go index 1fa8451..0038b64 100644 --- a/maputil/map.go +++ b/maputil/map.go @@ -110,6 +110,19 @@ func FilterByKeys[K comparable, V any](m map[K]V, keys []K) map[K]V { return result } +// FilterByValues iterates over map, return a new map whose values are all given values. +// todo: +func FilterByValues[K comparable, V comparable](m map[K]V, values []V) map[K]V { + result := make(map[K]V) + + for k, v := range m { + if slice.Contain(values, v) { + result[k] = v + } + } + return result +} + // Intersect iterates over maps, return a new map of key and value pairs in all given maps. // Play: https://go.dev/play/p/Zld0oj3sjcC func Intersect[K comparable, V any](maps ...map[K]V) map[K]V { diff --git a/maputil/map_test.go b/maputil/map_test.go index b2007d1..71fdd44 100644 --- a/maputil/map_test.go +++ b/maputil/map_test.go @@ -168,6 +168,25 @@ func TestFilterByKeys(t *testing.T) { }, acturl) } +func TestFilterByValues(t *testing.T) { + assert := internal.NewAssert(t, "TestFilterByValues") + + m := map[string]int{ + "a": 1, + "b": 2, + "c": 3, + "d": 4, + "e": 5, + } + + acturl := FilterByValues(m, []int{3, 4}) + + assert.Equal(map[string]int{ + "c": 3, + "d": 4, + }, acturl) +} + func TestIntersect(t *testing.T) { assert := internal.NewAssert(t, "TestIntersect")