-
Notifications
You must be signed in to change notification settings - Fork 0
/
slice.go
87 lines (69 loc) · 1.51 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
package utils
import (
"math/rand"
"time"
)
func RandShuffle(slice []interface{}) {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
r.Shuffle(len(slice), func(i, j int) {
slice[i], slice[j] = slice[j], slice[i]
})
}
func UniqueStr(slice []string) []string {
if len(slice) == 0 {
return slice
}
strMap := make(map[string]struct{}, len(slice))
newSlice := make([]string, 0, len(slice))
for _, item := range slice {
if _, ok := strMap[item]; ok {
continue
}
strMap[item] = struct{}{}
newSlice = append(newSlice, item)
}
return newSlice
}
func UniqueArray(iArray []int64) []int64 {
uniqueMap := make(map[int64]struct{})
result := make([]int64, 0, len(iArray))
for _, i := range iArray {
if _, ok := uniqueMap[i]; !ok {
result = append(result, i)
uniqueMap[i] = struct{}{}
}
}
return result
}
func IsInArray(item int, array []int) bool {
for _, arrayItem := range array {
if arrayItem == item {
return true
}
}
return false
}
func IsInStrArray(item string, array []string) bool {
for _, arrayItem := range array {
if arrayItem == item {
return true
}
}
return false
}
func ExcludeSlice(all, exclude []string) []string {
if len(all) == 0 || len(exclude) == 0 {
return all
}
excludeMap := make(map[string]struct{}, len(exclude))
for _, e := range exclude {
excludeMap[e] = struct{}{}
}
newSlice := make([]string, 0, len(all))
for _, item := range all {
if _, ok := excludeMap[item]; !ok {
newSlice = append(newSlice, item)
}
}
return newSlice
}