-
Notifications
You must be signed in to change notification settings - Fork 30
/
slice.go
96 lines (85 loc) · 1.53 KB
/
slice.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
package utils
func AppendIfUnique[T comparable](slice1 []T, slice2 []T) []T {
for _, i := range slice2 {
if !Contains(slice1, i) {
slice1 = append(slice1, i)
}
}
return slice1
}
func Contains[T comparable](s []T, e T) bool {
for _, v := range s {
if v == e {
return true
}
}
return false
}
func ContainsFunc[T any](s []T, f func(T) bool) bool {
for _, v := range s {
if f(v) {
return true
}
}
return false
}
func ContainsAny[T comparable](s []T, e []T) bool {
for _, v := range e {
if Contains(s, v) {
return true
}
}
return false
}
func Map[T1, T2 any](s []T1, f func(T1) T2) []T2 {
result := make([]T2, len(s))
for i, v := range s {
result[i] = f(v)
}
return result
}
func Filter[T any](s []T, f func(T) bool) []T {
result := make([]T, 0)
for _, v := range s {
if f(v) {
result = append(result, v)
}
}
return result
}
func FindFirst[T any](s []T, f func(T) bool) (T, bool) {
var t T
for _, v := range s {
if f(v) {
return v, true
}
}
return t, false
}
func Deduplicate[T comparable](s []T) []T {
// Create a map of all unique elements.
seen := make(map[T]struct{})
j := 0
for _, v := range s {
if _, ok := seen[v]; ok {
continue
}
seen[v] = struct{}{}
s[j] = v
j++
}
// Slice the map to create a new slice of unique elements.
return s[:j]
}
func Intersection(s1, s2 []string) (inter []string) {
m := make(map[string]bool)
for _, e := range s1 {
m[e] = true
}
for _, e := range s2 {
if m[e] {
inter = append(inter, e)
}
}
return Deduplicate(inter)
}