-
Notifications
You must be signed in to change notification settings - Fork 6
/
count.go
40 lines (36 loc) · 946 Bytes
/
count.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
package go2linq
import (
"iter"
"github.com/solsw/errorhelper"
)
// [Count] returns the number of elements in a sequence.
//
// [Count]: https://learn.microsoft.com/dotnet/api/system.linq.enumerable.count
func Count[Source any](source iter.Seq[Source]) (int, error) {
if source == nil {
return -1, errorhelper.CallerError(ErrNilSource)
}
res := 0
for range source {
res++
}
return res, nil
}
// [CountPred] returns a number that represents how many elements in a specified sequence satisfy a condition.
//
// [CountPred]: https://learn.microsoft.com/dotnet/api/system.linq.enumerable.count
func CountPred[Source any](source iter.Seq[Source], predicate func(Source) bool) (int, error) {
if source == nil {
return -1, errorhelper.CallerError(ErrNilSource)
}
if predicate == nil {
return -1, errorhelper.CallerError(ErrNilPredicate)
}
res := 0
for s := range source {
if predicate(s) {
res++
}
}
return res, nil
}