-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathslices.go
77 lines (65 loc) · 1.52 KB
/
slices.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
package gtl
// Contains returns whether `vs` contains the element `e` by comparing vs[i] == e.
func Contains[T comparable](vs []T, e T) bool {
for _, v := range vs {
if v == e {
return true
}
}
return false
}
// ExtractFrom extracts a nested object of type E from type T.
//
// This function is useful if we have a set of type `T` nad we want to
// extract the type E from any T.
func ExtractFrom[T, E any](set []T, fn func(T) E) []E {
r := make([]E, len(set))
for i := range set {
r[i] = fn(set[i])
}
return r
}
// Filter iterates over `set` and gets the values that match `criteria`.
//
// Filter will return a new allocated slice.
func Filter[T any](set []T, criteria func(T) bool) []T {
r := make([]T, 0)
for i := range set {
if criteria(set[i]) {
r = append(r, set[i])
}
}
return r
}
// FilterInPlace filters the contents of `set` using `criteria`.
//
// FilterInPlace returns `set`.
func FilterInPlace[T any](set []T, criteria func(T) bool) []T {
for i := 0; i < len(set); i++ {
if !criteria(set[i]) {
set = append(set[:i], set[i+1:]...)
i--
}
}
return set
}
// Delete the first occurrence of a type from a set.
func Delete[T comparable](set []T, value T) []T {
for i := 0; i < len(set); i++ {
if set[i] == value {
set = append(set[:i], set[i:]...)
break
}
}
return set
}
// DeleteAll occurrences from a set.
func DeleteAll[T comparable](set []T, value T) []T {
for i := 0; i < len(set); i++ {
if set[i] == value {
set = append(set[:i], set[i:]...)
i--
}
}
return set
}