-
Notifications
You must be signed in to change notification settings - Fork 0
/
mapper.go
39 lines (35 loc) · 996 Bytes
/
mapper.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
package streams
// Mapper is an interface for mapping (converting) one element type to another
type Mapper[T any, R any] interface {
// Map converts the values in the input Stream and produces a Stream of output types
Map(in Stream[T]) (Stream[R], error)
}
// NewMapper creates a new Mapper that will use the provided Converter
//
// NewMapper panics if a nil Converter is supplied
func NewMapper[T any, R any](c Converter[T, R]) Mapper[T, R] {
if c == nil {
panic("converter cannot be nil")
}
return mapper[T, R]{
c: c,
}
}
type mapper[T any, R any] struct {
c Converter[T, R]
}
// Map converts the values in the input stream and produces a stream of output types
func (m mapper[T, R]) Map(in Stream[T]) (Stream[R], error) {
r := make([]R, 0, in.Len())
if err := in.ForEach(NewConsumer[T](func(v T) error {
if a, err := m.c.Convert(v); err == nil {
r = append(r, a)
return nil
} else {
return err
}
})); err != nil {
return nil, err
}
return Of(r...), nil
}