forked from clipperhouse/slice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmaxby.go
24 lines (22 loc) · 771 Bytes
/
maxby.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
package sliceP
import "github.com/clipperhouse/typewriter"
var maxBy = &typewriter.Template{
Name: "MaxBy",
Text: `
// MaxBy returns an element of {{.SliceName}} containing the maximum value, when compared to other elements using a passed func defining ‘less’. In the case of multiple items being equally maximal, the last such element is returned. Returns error if no elements. See: http://clipperhouse.github.io/gen/#MaxBy
func (rcv {{.SliceName}}) MaxBy(less func({{.Type}}, {{.Type}}) bool) (result {{.Type}}, err error) {
l := len(rcv)
if l == 0 {
err = errors.New("cannot determine the MaxBy of an empty slice")
return
}
m := 0
for i := 1; i < l; i++ {
if rcv[i] != rcv[m] && !less(rcv[i], rcv[m]) {
m = i
}
}
result = rcv[m]
return
}
`}