-
Notifications
You must be signed in to change notification settings - Fork 6
/
join.go
69 lines (65 loc) · 2.38 KB
/
join.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
package go2linq
import (
"iter"
"sync"
"github.com/solsw/errorhelper"
"github.com/solsw/generichelper"
)
// [Join] correlates the elements of two sequences based on matching keys.
// [generichelper.DeepEqual] is used to compare keys.
// 'inner' is enumerated on the first iteration over the result.
//
// [Join]: https://learn.microsoft.com/dotnet/api/system.linq.enumerable.join
func Join[Outer, Inner, Key, Result any](outer iter.Seq[Outer], inner iter.Seq[Inner],
outerKeySelector func(Outer) Key, innerKeySelector func(Inner) Key,
resultSelector func(Outer, Inner) Result) (iter.Seq[Result], error) {
if outer == nil || inner == nil {
return nil, errorhelper.CallerError(ErrNilSource)
}
if outerKeySelector == nil || innerKeySelector == nil || resultSelector == nil {
return nil, errorhelper.CallerError(ErrNilSelector)
}
r, err := JoinEq(outer, inner, outerKeySelector, innerKeySelector, resultSelector, generichelper.DeepEqual[Key])
if err != nil {
return nil, errorhelper.CallerError(err)
}
return r, nil
}
// [JoinEq] correlates the elements of two sequences based on matching keys.
// 'equal' is used to compare keys.
// 'inner' is enumerated on the first iteration over the result.
//
// Similar to the keys equality functionality may be achieved using appropriate key selectors.
// See [TestJoinEqMust_CustomComparer] test for usage of case insensitive string keys.
//
// [JoinEq]: https://learn.microsoft.com/dotnet/api/system.linq.enumerable.join
func JoinEq[Outer, Inner, Key, Result any](outer iter.Seq[Outer], inner iter.Seq[Inner],
outerKeySelector func(Outer) Key, innerKeySelector func(Inner) Key,
resultSelector func(Outer, Inner) Result, equal func(Key, Key) bool) (iter.Seq[Result], error) {
if outer == nil || inner == nil {
return nil, errorhelper.CallerError(ErrNilSource)
}
if outerKeySelector == nil || innerKeySelector == nil || resultSelector == nil {
return nil, errorhelper.CallerError(ErrNilSelector)
}
if equal == nil {
return nil, errorhelper.CallerError(ErrNilEqual)
}
return func(yield func(Result) bool) {
var once sync.Once
var ilk *Lookup[Key, Inner]
for o := range outer {
once.Do(func() { ilk, _ = ToLookupEq(inner, innerKeySelector, equal) })
ii := ilk.itemSlice(outerKeySelector(o))
if len(ii) == 0 {
continue
}
for _, i := range ii {
if !yield(resultSelector(o, i)) {
return
}
}
}
},
nil
}