Skip to content

Commit

Permalink
feat: improve Union (#245)
Browse files Browse the repository at this point in the history
Co-authored-by: hhu <hhu@tencent.com>
  • Loading branch information
hhu-cc and hhu committed Oct 14, 2022
1 parent 3d0a3f8 commit 6a2a333
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 25 deletions.
33 changes: 8 additions & 25 deletions intersect.go
Expand Up @@ -141,35 +141,18 @@ func Difference[T comparable](list1 []T, list2 []T) ([]T, []T) {
return left, right
}

// Union returns all distinct elements from both collections.
// Union returns all distinct elements from given collections.
// result returns will not change the order of elements relatively.
func Union[T comparable](list1 []T, list2 []T) []T {
func Union[T comparable](lists ...[]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)
for _, list := range lists {
for _, e := range list {
if _, ok := seen[e]; !ok {
seen[e] = struct{}{}
result = append(result, e)
}
}
}

Expand Down
11 changes: 11 additions & 0 deletions intersect_test.go
Expand Up @@ -220,6 +220,17 @@ func TestUnion(t *testing.T) {
is.Equal(result3, []int{0, 1, 2, 3, 4, 5})
is.Equal(result4, []int{0, 1, 2})
is.Equal(result5, []int{})

result11 := Union([]int{0, 1, 2, 3, 4, 5}, []int{0, 2, 10}, []int{0, 1, 11})
result12 := Union([]int{0, 1, 2, 3, 4, 5}, []int{6, 7}, []int{8, 9})
result13 := Union([]int{0, 1, 2, 3, 4, 5}, []int{}, []int{})
result14 := Union([]int{0, 1, 2}, []int{0, 1, 2}, []int{0, 1, 2})
result15 := Union([]int{}, []int{}, []int{})
is.Equal(result11, []int{0, 1, 2, 3, 4, 5, 10, 11})
is.Equal(result12, []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9})
is.Equal(result13, []int{0, 1, 2, 3, 4, 5})
is.Equal(result14, []int{0, 1, 2})
is.Equal(result15, []int{})
}

func TestWithout(t *testing.T) {
Expand Down

0 comments on commit 6a2a333

Please sign in to comment.