-
Notifications
You must be signed in to change notification settings - Fork 6
/
Map.go
executable file
·58 lines (49 loc) · 1.29 KB
/
Map.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
package iterators
import (
"github.com/adamluzsi/frameless"
)
// Map allows you to do additional transformation on the values.
// This is useful in cases, where you have to alter the input value,
// or change the type all together.
// Like when you read lines from an input stream,
// and then you map the line content to a certain data structure,
// in order to not expose what steps needed in order to deserialize the input stream,
// thus protect the business rules from this information.
func Map[T any, V any](iter frameless.Iterator[T], transform MapTransformFunc[T, V]) *MapIter[T, V] {
return &MapIter[T, V]{Iterator: iter, Transform: transform}
}
type MapTransformFunc[T any, V any] func(T) (V, error)
type MapIter[T any, V any] struct {
Iterator frameless.Iterator[T]
Transform MapTransformFunc[T, V]
err error
value V
}
func (i *MapIter[T, V]) Close() error {
return i.Iterator.Close()
}
func (i *MapIter[T, V]) Next() bool {
if i.err != nil {
return false
}
ok := i.Iterator.Next()
if !ok {
return false
}
v, err := i.Transform(i.Iterator.Value())
if err != nil {
i.err = err
return false
}
i.value = v
return true
}
func (i *MapIter[T, V]) Err() error {
if i.err != nil {
return i.err
}
return i.Iterator.Err()
}
func (i *MapIter[T, V]) Value() V {
return i.value
}