-
Notifications
You must be signed in to change notification settings - Fork 4.4k
/
stringslice.go
70 lines (63 loc) · 1.39 KB
/
stringslice.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
package stringslice
// StrContains => Contains
// StringSliceEqual => Equal
// StringSliceMergeSorted => MergeSorted
// Contains checks if a list contains a string
func Contains(l []string, s string) bool {
for _, v := range l {
if v == s {
return true
}
}
return false
}
// Equal compares two string slices for equality. Both the existence
// of the elements and the order of those elements matter for equality. Empty
// slices are treated identically to nil slices.
func Equal(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if a[i] != b[i] {
return false
}
}
return true
}
// MergeSorted takes two string slices that are assumed to be sorted
// and does a zipper merge of the two sorted slices, removing any cross-slice
// duplicates. If any individual slice contained duplicates those will be
// retained.
func MergeSorted(a, b []string) []string {
if len(a) == 0 && len(b) == 0 {
return nil
} else if len(a) == 0 {
return b
} else if len(b) == 0 {
return a
}
out := make([]string, 0, len(a)+len(b))
i, j := 0, 0
for i < len(a) && j < len(b) {
switch {
case a[i] < b[j]:
out = append(out, a[i])
i++
case a[i] > b[j]:
out = append(out, b[j])
j++
default:
out = append(out, a[i])
i++
j++
}
}
if i < len(a) {
out = append(out, a[i:]...)
}
if j < len(b) {
out = append(out, b[j:]...)
}
return out
}