Skip to content

Instantly share code, notes, and snippets.

@maiah
Last active October 26, 2015 08:14
Show Gist options
  • Save maiah/8e458bddb058fa2c45b8 to your computer and use it in GitHub Desktop.
Save maiah/8e458bddb058fa2c45b8 to your computer and use it in GitHub Desktop.
Beautiful Streaming Filter, Map, and Collect using Channel Struct-wrapper
package main
import (
"fmt"
"strconv"
)
type Power struct {
up int
}
func main() {
s := []int{2, 3, 5, 7, 11, 13}
fmt.Println("s ==", s)
result := filter(s).
mapNow().
collect()
fmt.Println(result)
}
func filter(nums []int) Mapper {
m := Mapper{make(chan int)}
go func() {
for _, v := range nums {
if v > 3 && v < 13 {
m.channel <- v
}
}
close(m.channel)
}()
return m
}
type Mapper struct {
channel chan int
}
func (m Mapper) mapNow() Collector {
collector := Collector{make(chan Power)}
go func() {
for v := range m.channel {
collector.channel <- Power{v}
}
close(collector.channel)
}()
return collector
}
type Collector struct {
channel chan Power
}
func (c Collector) collect() string {
powers := "The powers: "
pow := 0
for v := range c.channel {
pow += v.up
}
return powers + strconv.Itoa(pow)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment