forked from blue-saber/summer
/
stream.go
83 lines (66 loc) · 1.55 KB
/
stream.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package summer
import (
"container/list"
"reflect"
)
type stream struct {
channel chan interface{}
}
func Stream(dataSlice interface{}) *stream {
s := &stream{channel: make(chan interface{})}
go func() {
for _, data := range interfaceSlice(dataSlice) {
s.channel <- data
}
close(s.channel)
}()
return s
}
func StreamOfList(aList *list.List) *stream {
s := &stream{channel: make(chan interface{})}
go func() {
for e := aList.Front(); e != nil; e = e.Next() {
s.channel <- e.Value
}
close(s.channel)
}()
return s
}
func interfaceSlice(slice interface{}) []interface{} {
s := reflect.ValueOf(slice)
if s.Kind() != reflect.Slice {
panic("InterfaceSlice() given a non-slice type")
}
ret := make([]interface{}, s.Len())
for i := 0; i < s.Len(); i++ {
ret[i] = s.Index(i).Interface()
}
return ret
}
func (inputStream *stream) ForEach(accept func(i interface{})) {
for data := range inputStream.channel {
accept(data)
}
}
func (inputStream *stream) Filter(predicate func(i interface{}) bool) *stream {
outputStream := &stream{channel: make(chan interface{})}
go func() {
for data := range inputStream.channel {
if predicate(data) {
outputStream.channel <- data
}
}
close(outputStream.channel)
}()
return outputStream
}
func (inputStream *stream) Map(apply func(i interface{}) interface{}) *stream {
outputStream := &stream{channel: make(chan interface{})}
go func() {
for data := range inputStream.channel {
outputStream.channel <- apply(data)
}
close(outputStream.channel)
}()
return outputStream
}