Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: improve Union #245

Merged
merged 1 commit into from Oct 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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