From 32ca975204c836865108e7eef2d27148fe6a06cc Mon Sep 17 00:00:00 2001 From: dudaodong Date: Tue, 21 Feb 2023 14:52:10 +0800 Subject: [PATCH] feat: add OmitBy, OmitByKeys, OmitByValues --- maputil/map.go | 39 ++++++++++++++++++++++++++++ maputil/map_test.go | 63 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 102 insertions(+) diff --git a/maputil/map.go b/maputil/map.go index 1dbc211..16e3976 100644 --- a/maputil/map.go +++ b/maputil/map.go @@ -123,6 +123,45 @@ func FilterByValues[K comparable, V comparable](m map[K]V, values []V) map[K]V { return result } +// OmitBy is the opposite of Filter, removes all the map elements for which the predicate function returns true. +// Play: todo +func OmitBy[K comparable, V any](m map[K]V, predicate func(key K, value V) bool) map[K]V { + result := make(map[K]V) + + for k, v := range m { + if !predicate(k, v) { + result[k] = v + } + } + return result +} + +// OmitByKeys the opposite of FilterByKeys, extracts all the map elements which keys are not omitted. +// Play: todo +func OmitByKeys[K comparable, V any](m map[K]V, keys []K) map[K]V { + result := make(map[K]V) + + for k, v := range m { + if !slice.Contain(keys, k) { + result[k] = v + } + } + return result +} + +// OmitByValues the opposite of FilterByValues. remov all elements whose value are in the give slice. +// Play: todo +func OmitByValues[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 e27f1c4..13f62d4 100644 --- a/maputil/map_test.go +++ b/maputil/map_test.go @@ -188,6 +188,69 @@ func TestFilterByValues(t *testing.T) { }, acturl) } +func TestOmitBy(t *testing.T) { + assert := internal.NewAssert(t, "TestOmitBy") + + m := map[string]int{ + "a": 1, + "b": 2, + "c": 3, + "d": 4, + "e": 5, + } + isEven := func(_ string, value int) bool { + return value%2 == 0 + } + + acturl := OmitBy(m, isEven) + + assert.Equal(map[string]int{ + "a": 1, + "c": 3, + "e": 5, + }, acturl) +} + +func TestOmitByKeys(t *testing.T) { + assert := internal.NewAssert(t, "TestOmitByKeys") + + m := map[string]int{ + "a": 1, + "b": 2, + "c": 3, + "d": 4, + "e": 5, + } + + acturl := OmitByKeys(m, []string{"a", "b"}) + + assert.Equal(map[string]int{ + "c": 3, + "d": 4, + "e": 5, + }, acturl) +} + +func TestOmitByValues(t *testing.T) { + assert := internal.NewAssert(t, "TestOmitByValues") + + m := map[string]int{ + "a": 1, + "b": 2, + "c": 3, + "d": 4, + "e": 5, + } + + acturl := OmitByValues(m, []int{4, 5}) + + assert.Equal(map[string]int{ + "a": 1, + "b": 2, + "c": 3, + }, acturl) +} + func TestIntersect(t *testing.T) { assert := internal.NewAssert(t, "TestIntersect")