forked from reusee/taobao-old
-
Notifications
You must be signed in to change notification settings - Fork 0
/
trace_utils.go
100 lines (85 loc) · 1.62 KB
/
trace_utils.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
97
98
99
100
package taobao
import (
"math/rand"
"sort"
)
type Traces []*Trace
func (s Traces) Reduce(initial interface{}, fn func(value interface{}, elem *Trace) interface{}) (ret interface{}) {
ret = initial
for _, elem := range s {
ret = fn(ret, elem)
}
return
}
func (s Traces) Map(fn func(*Trace) *Trace) (ret Traces) {
for _, elem := range s {
ret = append(ret, fn(elem))
}
return
}
func (s Traces) Filter(filter func(*Trace) bool) (ret Traces) {
for _, elem := range s {
if filter(elem) {
ret = append(ret, elem)
}
}
return
}
func (s Traces) All(predict func(*Trace) bool) (ret bool) {
ret = true
for _, elem := range s {
ret = predict(elem) && ret
}
return
}
func (s Traces) Any(predict func(*Trace) bool) (ret bool) {
for _, elem := range s {
ret = predict(elem) || ret
}
return
}
func (s Traces) Each(fn func(e *Trace)) {
for _, elem := range s {
fn(elem)
}
}
func (s Traces) Shuffle() {
for i := len(s) - 1; i >= 1; i-- {
j := rand.Intn(i + 1)
s[i], s[j] = s[j], s[i]
}
}
func (s Traces) Sort(cmp func(a, b *Trace) bool) {
sorter := sliceSorter{
l: len(s),
less: func(i, j int) bool {
return cmp(s[i], s[j])
},
swap: func(i, j int) {
s[i], s[j] = s[j], s[i]
},
}
_ = sorter.Len
_ = sorter.Less
_ = sorter.Swap
sort.Sort(sorter)
}
type sliceSorter struct {
l int
less func(i, j int) bool
swap func(i, j int)
}
func (t sliceSorter) Len() int {
return t.l
}
func (t sliceSorter) Less(i, j int) bool {
return t.less(i, j)
}
func (t sliceSorter) Swap(i, j int) {
t.swap(i, j)
}
func (s Traces) Clone() (ret Traces) {
ret = make([]*Trace, len(s))
copy(ret, s)
return
}