forked from clipperhouse/slice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsortby.go
61 lines (56 loc) · 1.88 KB
/
sortby.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
package sliceP
import "github.com/clipperhouse/typewriter"
var sortBy = &typewriter.Template{
Name: "SortBy",
Text: `
// SortBy returns a new ordered {{.SliceName}}, determined by a func defining ‘less’. See: http://clipperhouse.github.io/gen/#SortBy
func (rcv {{.SliceName}}) SortBy(less func({{.Type}}, {{.Type}}) bool) {{.SliceName}} {
result := make({{.SliceName}}, len(rcv))
copy(result, rcv)
// Switch to heapsort if depth of 2*ceil(lg(n+1)) is reached.
n := len(result)
maxDepth := 0
for i := n; i > 0; i >>= 1 {
maxDepth++
}
maxDepth *= 2
quickSort{{.SliceName}}(result, less, 0, n, maxDepth)
return result
}
`}
var isSortedBy = &typewriter.Template{
Name: "IsSortedBy",
Text: `
// IsSortedBy reports whether an instance of {{.SliceName}} is sorted, using the pass func to define ‘less’. See: http://clipperhouse.github.io/gen/#SortBy
func (rcv {{.SliceName}}) IsSortedBy(less func({{.Type}}, {{.Type}}) bool) bool {
n := len(rcv)
for i := n - 1; i > 0; i-- {
if less(rcv[i], rcv[i-1]) {
return false
}
}
return true
}
`}
var sortByDesc = &typewriter.Template{
Name: "SortByDesc",
Text: `
// SortByDesc returns a new, descending-ordered {{.SliceName}}, determined by a func defining ‘less’. See: http://clipperhouse.github.io/gen/#SortBy
func (rcv {{.SliceName}}) SortByDesc(less func({{.Type}}, {{.Type}}) bool) {{.SliceName}} {
greater := func(a, b {{.Type}}) bool {
return less(b, a)
}
return rcv.SortBy(greater)
}
`}
var isSortedByDesc = &typewriter.Template{
Name: "IsSortedByDesc",
Text: `
// IsSortedDesc reports whether an instance of {{.SliceName}} is sorted in descending order, using the pass func to define ‘less’. See: http://clipperhouse.github.io/gen/#SortBy
func (rcv {{.SliceName}}) IsSortedByDesc(less func({{.Type}}, {{.Type}}) bool) bool {
greater := func(a, b {{.Type}}) bool {
return less(b, a)
}
return rcv.IsSortedBy(greater)
}
`}