/
util.go
78 lines (60 loc) · 1.35 KB
/
util.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
package goist
import (
"math/rand"
"reflect"
"sort"
"time"
)
func Unique(slicePtr interface{}) {
var j []int
m := make(map[interface{}]bool)
if reflect.TypeOf(slicePtr).Elem().Kind() != reflect.Slice {
return
}
s := reflect.ValueOf(slicePtr).Elem()
if s.Len() < 1 {
return
}
for i := 0; i < s.Len(); i++ {
if _, ok := m[s.Index(i).Interface()]; ok {
j = append(j, i)
continue
}
m[s.Index(i).Interface()] = true
}
sort.Slice(j, func(i, j int) bool {
return i > j
})
for _, v := range j {
s = reflect.AppendSlice(s.Slice(0, v), s.Slice(v+1, s.Len()))
}
reflect.ValueOf(slicePtr).Elem().Set(s)
}
func Contains(slice interface{}, item interface{}) bool {
switch reflect.TypeOf(slice).Kind() {
case reflect.Slice, reflect.Array:
s := reflect.ValueOf(slice)
for i := 0; i < s.Len(); i++ {
if s.Index(i).Interface() == item {
return true
}
}
}
return false
}
func Rand() *rand.Rand {
return rand.New(rand.NewSource(time.Now().UnixNano()))
}
func Retry(attempts int, sleep time.Duration, f func() error) error {
if err := f(); err != nil {
if attempts--; attempts > 0 {
// Add some randomness to prevent creating a Thundering Herd
jitter := time.Duration(Rand().Int63n(int64(sleep)))
sleep = sleep + jitter/2
time.Sleep(sleep)
return Retry(attempts, 2*sleep, f)
}
return err
}
return nil
}