-
Notifications
You must be signed in to change notification settings - Fork 14
/
sets.go
110 lines (92 loc) · 1.81 KB
/
sets.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package strmangle
// SetInclude checks to see if the string is found in the string slice
func SetInclude(str string, slice []string) bool {
for _, s := range slice {
if str == s {
return true
}
}
return false
}
// SetComplement subtracts the elements in b from a
func SetComplement(a []string, b []string) []string {
c := make([]string, 0, len(a))
for _, aVal := range a {
found := false
for _, bVal := range b {
if aVal == bVal {
found = true
break
}
}
if !found {
c = append(c, aVal)
}
}
return c
}
// SetMerge will return a merged slice without duplicates
func SetMerge(a []string, b []string) []string {
merged := make([]string, 0, len(a)+len(b))
for _, aVal := range a {
found := false
for _, mVal := range merged {
if aVal == mVal {
found = true
break
}
}
if !found {
merged = append(merged, aVal)
}
}
for _, bVal := range b {
found := false
for _, mVal := range merged {
if bVal == mVal {
found = true
break
}
}
if !found {
merged = append(merged, bVal)
}
}
return merged
}
// SetIntersect will return all elements present in both a and b
func SetIntersect(a []string, b []string) []string {
intersection := make([]string, 0)
for _, aVal := range a {
for _, bVal := range b {
if aVal == bVal {
intersection = append(intersection, aVal)
break
}
}
}
return intersection
}
// SortByKeys returns a new ordered slice based on the keys ordering
func SortByKeys(keys []string, strs []string) []string {
resultLen := len(strs)
if len(keys) < len(strs) {
resultLen = len(keys)
}
c := make([]string, resultLen)
index := 0
Outer:
for _, v := range keys {
for _, k := range strs {
if v == k {
c[index] = v
index++
if index > len(strs)-1 {
break Outer
}
break
}
}
}
return c
}