diff --git a/maputil/map.go b/maputil/map.go index a22988f..dcb6bb9 100644 --- a/maputil/map.go +++ b/maputil/map.go @@ -60,7 +60,7 @@ func Filter[K comparable, V any](m map[K]V, predicate func(key K, value V) bool) return res } -// Intersect iterates over maps, return a new map of key and value pairs in all give maps +// Intersect iterates over maps, return a new map of key and value pairs in all given maps func Intersect[K comparable, V any](maps ...map[K]V) map[K]V { if len(maps) == 0 { return map[K]V{} @@ -92,3 +92,16 @@ func Intersect[K comparable, V any](maps ...map[K]V) map[K]V { return res } + + +// Minus creates an map of whose key in mapA but not in mapB +func Minus[K comparable, V any](mapA, mapB map[K]V) map[K]V { + res := make(map[K]V) + + for k, v := range mapA { + if _, ok := mapB[k]; !ok { + res[k] = v + } + } + return res +} diff --git a/maputil/map_test.go b/maputil/map_test.go index 7957c09..1c5d1a6 100644 --- a/maputil/map_test.go +++ b/maputil/map_test.go @@ -130,3 +130,21 @@ func TestIntersect(t *testing.T) { assert.Equal(map[string]int{"a": 1, "b": 2}, Intersect(m1, m2)) assert.Equal(map[string]int{"a": 1}, Intersect(m1, m2, m3)) } + +func TestMinus(t *testing.T) { + assert := internal.NewAssert(t, "TestMinus") + + m1 := map[string]int{ + "a": 1, + "b": 2, + "c": 3, + } + + m2 := map[string]int{ + "a": 11, + "b": 22, + "d": 33, + } + + assert.Equal(map[string]int{"c": 3}, Minus(m1, m2)) +}