forked from clipperhouse/slice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
max.go
53 lines (50 loc) · 1.42 KB
/
max.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
package sliceP
import "github.com/clipperhouse/typewriter"
var max = &typewriter.Template{
Name: "Max",
Text: `
// Max returns the maximum value of {{.SliceName}}. In the case of multiple items being equally maximal, the first such element is returned. Returns error if no elements. See: http://clipperhouse.github.io/gen/#Max
func (rcv {{.SliceName}}) Max() (result {{.Type}}, err error) {
l := len(rcv)
if l == 0 {
err = errors.New("cannot determine the Max of an empty slice")
return
}
result = rcv[0]
for _, v := range rcv {
if v > result {
result = v
}
}
return
}
`,
TypeConstraint: typewriter.Constraint{Ordered: true},
}
var maxT = &typewriter.Template{
Name: "Max",
Text: `
// Max{{.TypeParameter.LongName}} selects the largest value of {{.TypeParameter}} in {{.SliceName}}. Returns error on {{.SliceName}} with no elements. See: http://clipperhouse.github.io/gen/#MaxCustom
func (rcv {{.SliceName}}) Max{{.TypeParameter.LongName}}(fn func({{.Type}}) {{.TypeParameter}}) (result {{.TypeParameter}}, err error) {
l := len(rcv)
if l == 0 {
err = errors.New("cannot determine Max of zero-length {{.SliceName}}")
return
}
result = fn(rcv[0])
if l > 1 {
for _, v := range rcv[1:] {
f := fn(v)
if f > result {
result = f
}
}
}
return
}
`,
TypeParameterConstraints: []typewriter.Constraint{
// exactly one type parameter is required, and it must be ordered
{Ordered: true},
},
}