-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsort.go
95 lines (82 loc) · 1.69 KB
/
sort.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
package gostream
import (
"math/rand"
"sort"
)
// SortedBy ...
func (s Stream) SortedBy(selector normalizedFn) Stream {
less := func(a, b interface{}) bool {
x, y := selector(a), selector(b)
c := getComparer(x)
res := c(x, y)
return res < 0
}
return s.Sorted(less)
}
// SortedDescBy ...
func (s Stream) SortedDescBy(selector normalizedFn) Stream {
less := func(a, b interface{}) bool {
x, y := selector(a), selector(b)
c := getComparer(x)
res := c(x, y)
return res > 0
}
return s.Sorted(less)
}
// Sorted 按Less函数排序
// 参数说明
//
// less函数。 a, b 为item,若a小于b(a排b前面)返回true
func (s Stream) Sorted(less lessFn) Stream {
return Stream{
Iterate: func() Iterator {
var items []interface{}
next := s.Iterate()
for item, ok := next(); ok; item, ok = next() {
items = append(items, item)
}
itemLen := len(items)
index := 0
if itemLen > 0 {
sort.Slice(items, func(i, j int) bool {
return less(items[i], items[j])
})
}
return func() (item interface{}, ok bool) {
ok = index < itemLen
if ok {
item = items[index]
index++
}
return
}
},
}
}
// Shuffle ...
func (s Stream) Shuffle() Stream {
return Stream{
Iterate: func() Iterator {
var items []interface{}
next := s.Iterate()
for item, ok := next(); ok; item, ok = next() {
items = append(items, item)
}
itemLen := len(items)
index := 0
if itemLen > 0 {
rand.Shuffle(itemLen, func(i, j int) {
items[i], items[j] = items[j], items[i]
})
}
return func() (item interface{}, ok bool) {
ok = index < itemLen
if ok {
item = items[index]
index++
}
return
}
},
}
}