-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstreams.go
More file actions
96 lines (87 loc) · 2.4 KB
/
Copy pathstreams.go
File metadata and controls
96 lines (87 loc) · 2.4 KB
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package functools
// streamable is a collection that processes data on-demand via channels
type streamable[InputType any] struct {
stream <-chan InputType
}
// Creates a streamable from a slice
func Streamify[InputType any](items []InputType) *streamable[InputType] {
ch := make(chan InputType)
go func() {
defer close(ch)
for _, v := range items {
ch <- v
}
}()
return &streamable[InputType]{stream: ch}
}
// CreateStream creates a streamable by receiving a generator function
// that generates values and sends them through the provided channel.
func CreateStream[InputType any](generator func(chan InputType)) *streamable[InputType] {
ch := make(chan InputType)
go func() {
defer close(ch)
generator(ch) // Call the generator with the channel
}()
return &streamable[InputType]{stream: ch}
}
// Pipe creates a new streamable by applying fn to each item
func (s *streamable[InputType]) Pipe(fn func(InputType) any) *streamable[any] {
out := make(chan any)
go func() {
defer close(out)
for v := range s.stream {
out <- fn(v)
}
}()
return &streamable[any]{stream: out}
}
// Filter creates a new streamable by filtering items with fn
func (s *streamable[InputType]) Filter(fn func(InputType) bool) *streamable[InputType] {
out := make(chan InputType)
go func() {
defer close(out)
for v := range s.stream {
if fn(v) {
out <- v
}
}
}()
return &streamable[InputType]{stream: out}
}
// ForEach consumes the stream by applying fn to each item
func (s *streamable[InputType]) ForEach(fn func(InputType)) {
for v := range s.stream {
fn(v)
}
}
// ToSlice collects all items into a slice (may block until everything is consumed)
func (s *streamable[InputType]) ToSlice() []InputType {
var result []InputType
for v := range s.stream {
result = append(result, v)
}
return result
}
func (s *streamable[InputType]) ToBufferedStream(bufferSize int) *bufferedStream[InputType] {
ch := make(chan InputType, bufferSize)
go func() {
defer close(ch)
for v := range s.stream {
ch <- v
}
}()
return &bufferedStream[InputType]{stream: ch}
}
func RecastStream[StreamType any](s *streamable[any]) *streamable[StreamType] {
out := make(chan StreamType)
go func() {
defer close(out)
for v := range s.stream {
// Attempt to cast each item in the stream to OutputType
if casted, ok := v.(StreamType); ok {
out <- casted
}
}
}()
return &streamable[StreamType]{stream: out}
}