-
Notifications
You must be signed in to change notification settings - Fork 0
/
intersect.go
85 lines (68 loc) · 1.72 KB
/
intersect.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package lo
// Contains returns true if an element is present in a collection.
func Contains[T comparable](collection []T, element T) bool {
for _, item := range collection {
if item == element {
return true
}
}
return false
}
// Every returns true if all elements of a subset are contained into a collection.
func Every[T comparable](collection []T, subset []T) bool {
for _, elem := range subset {
if !Contains(collection, elem) {
return false
}
}
return true
}
// Some returns true if at least 1 element of a subset is contained into a collection.
func Some[T comparable](collection []T, subset []T) bool {
for _, elem := range subset {
if Contains(collection, elem) {
return true
}
}
return false
}
// Intersect returns the intersection between two collections.
func Intersect[T comparable](list1 []T, list2 []T) []T {
result := []T{}
seen := map[T]bool{}
for _, elem := range list1 {
seen[elem] = true
}
for _, elem := range list2 {
if _, ok := seen[elem]; ok {
result = append(result, elem)
}
}
return result
}
// Difference returns the difference between two collections.
// The first value is the collection of element absent of list2.
// The second value is the collection of element absent of list1.
func Difference[T comparable](list1 []T, list2 []T) ([]T, []T) {
left := []T{}
right := []T{}
seenLeft := map[T]bool{}
seenRight := map[T]bool{}
for _, elem := range list1 {
seenLeft[elem] = true
}
for _, elem := range list2 {
seenRight[elem] = true
}
for _, elem := range list1 {
if _, ok := seenRight[elem]; !ok {
left = append(left, elem)
}
}
for _, elem := range list2 {
if _, ok := seenLeft[elem]; !ok {
right = append(right, elem)
}
}
return left, right
}