forked from clipperhouse/slice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsingle.go
29 lines (27 loc) · 777 Bytes
/
single.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
package slice
import "github.com/clipperhouse/typewriter"
var single = &typewriter.Template{
Name: "Single",
Text: `
// Single returns exactly one element of {{.SliceName}} that returns true for the passed func. Returns error if no or multiple elements return true. See: http://clipperhouse.github.io/gen/#Single
func (rcv {{.SliceName}}) Single(fn func({{.Type}}) bool) (result {{.Type}}, err error) {
var candidate {{.Type}}
found := false
for _, v := range rcv {
if fn(v) {
if found {
err = errors.New("multiple {{.SliceName}} elements return true for passed func")
return
}
candidate = v
found = true
}
}
if found {
result = candidate
} else {
err = errors.New("no {{.SliceName}} elements return true for passed func")
}
return
}
`}