-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathintersect.go
57 lines (52 loc) · 2.24 KB
/
intersect.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
package go2linq
import (
"iter"
"github.com/solsw/errorhelper"
"github.com/solsw/generichelper"
)
// [Intersect] produces the set intersection of two sequences using [generichelper.DeepEqual] to compare values.
// 'second' is enumerated on the first iteration over the result.
// Order of elements in the result corresponds to the order of elements in 'first'.
//
// [Intersect]: https://learn.microsoft.com/dotnet/api/system.linq.enumerable.intersect
func Intersect[Source any](first, second iter.Seq[Source]) (iter.Seq[Source], error) {
if first == nil || second == nil {
return nil, errorhelper.CallerError(ErrNilSource)
}
r, err := IntersectEq(first, second, generichelper.DeepEqual[Source])
if err != nil {
return nil, errorhelper.CallerError(err)
}
return r, nil
}
// [IntersectEq] produces the set intersection of two sequences using 'equal' to compare values.
// 'second' is enumerated on the first iteration over the result.
// Order of elements in the result corresponds to the order of elements in 'first'.
//
// [IntersectEq]: https://learn.microsoft.com/dotnet/api/system.linq.enumerable.intersect
func IntersectEq[Source any](first, second iter.Seq[Source], equal func(Source, Source) bool) (iter.Seq[Source], error) {
if first == nil || second == nil {
return nil, errorhelper.CallerError(ErrNilSource)
}
if equal == nil {
return nil, errorhelper.CallerError(ErrNilEqual)
}
return seqIntersectByEq(first, second, Identity[Source], equal, equal, nil),
nil
}
// [IntersectCmp] produces the set intersection of two sequences using 'comparer' to compare values. (See [DistinctCmp].)
// 'second' is enumerated on the first iteration over the result.
// Order of elements in the result corresponds to the order of elements in 'first'.
//
// [IntersectCmp]: https://learn.microsoft.com/dotnet/api/system.linq.enumerable.intersect
func IntersectCmp[Source any](first, second iter.Seq[Source], compare func(Source, Source) int) (iter.Seq[Source], error) {
if first == nil || second == nil {
return nil, errorhelper.CallerError(ErrNilSource)
}
if compare == nil {
return nil, errorhelper.CallerError(ErrNilCompare)
}
return seqIntersectByEq(first, second, Identity[Source],
func(a, b Source) bool { return compare(a, b) == 0 }, nil, compare),
nil
}