-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathdistinctby.go
87 lines (82 loc) · 2.57 KB
/
distinctby.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package go2linq
import (
"iter"
"github.com/solsw/errorhelper"
"github.com/solsw/generichelper"
)
// [DistinctBy] returns distinct elements from a sequence according to
// a specified key selector function and using [generichelper.DeepEqual] to compare keys.
//
// [DistinctBy]: https://learn.microsoft.com/dotnet/api/system.linq.enumerable.distinctby
func DistinctBy[Source, Key any](source iter.Seq[Source], keySelector func(Source) Key) (iter.Seq[Source], error) {
if source == nil {
return nil, errorhelper.CallerError(ErrNilSource)
}
if keySelector == nil {
return nil, errorhelper.CallerError(ErrNilSelector)
}
r, err := DistinctByEq(source, keySelector, generichelper.DeepEqual[Key])
if err != nil {
return nil, errorhelper.CallerError(err)
}
return r, nil
}
// [DistinctByEq] returns distinct elements from a sequence according to
// a specified key selector function and using a specified 'keyEqual' to compare keys.
//
// [DistinctByEq]: https://learn.microsoft.com/dotnet/api/system.linq.enumerable.distinctby
func DistinctByEq[Source, Key any](source iter.Seq[Source],
keySelector func(Source) Key, keyEqual func(Key, Key) bool) (iter.Seq[Source], error) {
if source == nil {
return nil, errorhelper.CallerError(ErrNilSource)
}
if keySelector == nil {
return nil, errorhelper.CallerError(ErrNilSelector)
}
if keyEqual == nil {
return nil, errorhelper.CallerError(ErrNilEqual)
}
return func(yield func(Source) bool) {
var seen []Key
for s := range source {
k := keySelector(s)
if !elInElelEq(k, seen, keyEqual) {
seen = append(seen, k)
if !yield(s) {
return
}
}
}
},
nil
}
// [DistinctByCmp] returns distinct elements from a sequence according to a specified key selector function
// and using a specified 'compare' to compare keys. (See [DistinctCmp].)
//
// [DistinctByCmp]: https://learn.microsoft.com/dotnet/api/system.linq.enumerable.distinctby
func DistinctByCmp[Source, Key any](source iter.Seq[Source],
keySelector func(Source) Key, compare func(Key, Key) int) (iter.Seq[Source], error) {
if source == nil {
return nil, errorhelper.CallerError(ErrNilSource)
}
if keySelector == nil {
return nil, errorhelper.CallerError(ErrNilSelector)
}
if compare == nil {
return nil, errorhelper.CallerError(ErrNilCompare)
}
return func(yield func(Source) bool) {
seen := make([]Key, 0)
for s := range source {
k := keySelector(s)
i := elIdxInElelCmp(k, seen, compare)
if i == len(seen) || compare(k, seen[i]) != 0 {
elIntoElelAtIdx(k, &seen, i)
if !yield(s) {
return
}
}
}
},
nil
}