-
Notifications
You must be signed in to change notification settings - Fork 6
/
zip.go
48 lines (43 loc) · 1.67 KB
/
zip.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
package go2linq
import (
"github.com/solsw/errorhelper"
)
// Reimplementing LINQ to Objects: Part 35 – Zip
// https://codeblog.jonskeet.uk/2011/01/14/reimplementing-linq-to-objects-part-35-zip/
// https://learn.microsoft.com/dotnet/api/system.linq.enumerable.zip
func factoryZip[First, Second, Result any](first Enumerable[First], second Enumerable[Second],
resultSelector func(First, Second) Result) func() Enumerator[Result] {
return func() Enumerator[Result] {
enr1 := first.GetEnumerator()
enr2 := second.GetEnumerator()
return enrFunc[Result]{
mvNxt: func() bool {
if enr1.MoveNext() && enr2.MoveNext() {
return true
}
return false
},
crrnt: func() Result { return resultSelector(enr1.Current(), enr2.Current()) },
rst: func() { enr1.Reset(); enr2.Reset() },
}
}
}
// [Zip] applies a specified function to the corresponding elements
// of two sequences, producing a sequence of the results.
//
// [Zip]: https://learn.microsoft.com/dotnet/api/system.linq.enumerable.zip
func Zip[First, Second, Result any](first Enumerable[First], second Enumerable[Second],
resultSelector func(First, Second) Result) (Enumerable[Result], error) {
if first == nil || second == nil {
return nil, errorhelper.CallerError(ErrNilSource)
}
if resultSelector == nil {
return nil, errorhelper.CallerError(ErrNilSelector)
}
return OnFactory(factoryZip(first, second, resultSelector)), nil
}
// ZipMust is like [Zip] but panics in case of error.
func ZipMust[First, Second, Result any](first Enumerable[First], second Enumerable[Second],
resultSelector func(First, Second) Result) Enumerable[Result] {
return errorhelper.Must(Zip(first, second, resultSelector))
}