mirror of
https://github.com/samber/lo.git
synced 2025-09-26 20:11:13 +08:00
Add Union
This commit is contained in:
35
intersect.go
35
intersect.go
@@ -94,3 +94,38 @@ func Difference[T comparable](list1 []T, list2 []T) ([]T, []T) {
|
||||
|
||||
return left, right
|
||||
}
|
||||
|
||||
// Union returns all distinct elements from both collections.
|
||||
// result returns will not change the order of elements relatively.
|
||||
func Union[T comparable](list1 []T, list2 []T) []T {
|
||||
result := []T{}
|
||||
|
||||
seen := map[T]struct{}{}
|
||||
hasAdd := map[T]struct{}{}
|
||||
|
||||
for _, e := range list1 {
|
||||
seen[e] = struct{}{}
|
||||
}
|
||||
|
||||
for _, e := range list2 {
|
||||
seen[e] = struct{}{}
|
||||
}
|
||||
|
||||
for _, e := range list1 {
|
||||
if _, ok := seen[e]; ok {
|
||||
result = append(result, e)
|
||||
hasAdd[e] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
for _, e := range list2 {
|
||||
if _, ok := hasAdd[e]; ok {
|
||||
continue
|
||||
}
|
||||
if _, ok := seen[e]; ok {
|
||||
result = append(result, e)
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
@@ -93,3 +93,17 @@ func TestDifference(t *testing.T) {
|
||||
is.Equal(left3, []int{})
|
||||
is.Equal(right3, []int{})
|
||||
}
|
||||
|
||||
func TestUnion(t *testing.T) {
|
||||
is := assert.New(t)
|
||||
result1 := Union[int]([]int{0, 1, 2, 3, 4, 5}, []int{0, 2, 10})
|
||||
result2 := Union[int]([]int{0, 1, 2, 3, 4, 5}, []int{6, 7})
|
||||
result3 := Union[int]([]int{0, 1, 2, 3, 4, 5}, []int{})
|
||||
result4 := Union[int]([]int{0, 1, 2}, []int{0, 1, 2})
|
||||
result5 := Union[int]([]int{}, []int{})
|
||||
is.Equal(result1, []int{0, 1, 2, 3, 4, 5, 10})
|
||||
is.Equal(result2, []int{0, 1, 2, 3, 4, 5, 6, 7})
|
||||
is.Equal(result3, []int{0, 1, 2, 3, 4, 5})
|
||||
is.Equal(result4, []int{0, 1, 2})
|
||||
is.Equal(result5, []int{})
|
||||
}
|
||||
|
Reference in New Issue
Block a user