-
Notifications
You must be signed in to change notification settings - Fork 2
/
slice.go
73 lines (57 loc) · 1.4 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
package sugar
import "golang.org/x/exp/constraints"
func SliceFiltrate[V any](collection []V, filtrate func(V, int) bool) []V {
result := []V{}
for i, v := range collection {
if filtrate(v, i) {
result = append(result, v)
}
}
return result
}
func SliceUpdateElement[T any, R any](collection []T, iteratee func(T, int) R) []R {
result := make([]R, len(collection))
for i, t := range collection {
result[i] = iteratee(t, i)
}
return result
}
func SliceUniq[T any, U comparable](collection []T, iteratee func(T) U) []T {
result := make([]T, len(collection))
seen := make(map[U]struct{}, len(collection))
for _, item := range collection {
key := iteratee(item)
if _, ok := seen[key]; ok {
continue
}
seen[key] = struct{}{}
}
return result
}
func SliceGroupBy[T any, U comparable](collection []T, iteratee func(T) U) map[U][]T {
result := map[U][]T{}
for _, item := range collection {
key := iteratee(item)
result[key] = append(result[key], item)
}
return result
}
//CheckInSlice check value in slice
func CheckInSlice[T constraints.Ordered](a T, s []T) bool {
for _, val := range s {
if a == val {
return true
}
}
return false
}
//DelOneInSlice delete one element of slice left->right
func DelOneInSlice[T constraints.Ordered](a T, old []T) (new []T) {
for i, val := range old {
if a == val {
new = append(old[:i], old[i+1:]...)
return
}
}
return old
}