diff --git a/README.md b/README.md index f5d614d..2f56cba 100644 --- a/README.md +++ b/README.md @@ -292,6 +292,7 @@ import "github.com/duke-git/lancet/v2/maputil" - [Merge](https://github.com/duke-git/lancet/blob/main/docs/maputil.md#Merge) - [Minus](https://github.com/duke-git/lancet/blob/main/docs/maputil.md#Minus) - [Values](https://github.com/duke-git/lancet/blob/main/docs/maputil.md#Values) +- [IsDisjoint](https://github.com/duke-git/lancet/blob/main/docs/maputil.md#IsDisjoint) ### 11. Mathutil package implements some functions for math calculation. diff --git a/docs/maputil.md b/docs/maputil.md index ce4b334..75c62db 100644 --- a/docs/maputil.md +++ b/docs/maputil.md @@ -301,4 +301,54 @@ func main() { fmt.Println(values) // []string{"a", "a", "b", "c", "d"} } +``` + +### Values +
Returns a boolean
+ +Signature: + +```go +IsDisjoint[K comparable, V any](mapA, mapB map[K]V) bool +``` +Example: + +```go +package main + +import ( + "fmt" + "github.com/duke-git/lancet/v2/maputil" +) + +func main() { + m1 := map[int]string{ + 1: "a", + 2: "a", + 3: "b", + 4: "c", + 5: "d", + } + + m2 := map[int]string{ + 1: "a", + 2: "a", + 3: "b", + 4: "c", + 5: "d", + } + + m3 := map[int]string{ + 6: "a", + } + + ok := maputil.IsDisjoint(m2, m1) + + fmt.Println(ok) // false + + + ok = maputil.IsDisjoint(m2, m3) + + fmt.Println(ok) // true +} ``` \ No newline at end of file diff --git a/maputil/map.go b/maputil/map.go index 09d19bf..55d08e1 100644 --- a/maputil/map.go +++ b/maputil/map.go @@ -108,3 +108,13 @@ func Minus[K comparable, V any](mapA, mapB map[K]V) map[K]V { } return result } + +// IsDisjoint two map are disjoint if they have no keys in common +func IsDisjoint[K comparable, V any](mapA, mapB map[K]V) bool { + for k := range mapA { + if _, ok := mapB[k]; ok { + return false + } + } + return true +} diff --git a/maputil/map_test.go b/maputil/map_test.go index 1c5d1a6..53ad992 100644 --- a/maputil/map_test.go +++ b/maputil/map_test.go @@ -148,3 +148,25 @@ func TestMinus(t *testing.T) { assert.Equal(map[string]int{"c": 3}, Minus(m1, m2)) } + +func TestIsDisjoint(t *testing.T) { + assert := internal.NewAssert(t, "TestMinus") + + m1 := map[string]int{ + "a": 1, + "b": 2, + "c": 3, + } + + m2 := map[string]int{ + "d": 22, + } + + assert.Equal(true, IsDisjoint(m1, m2)) + + m3 := map[string]int{ + "a": 22, + } + + assert.Equal(false, IsDisjoint(m1, m3)) +}