Last active
October 26, 2015 08:14
-
-
Save maiah/8e458bddb058fa2c45b8 to your computer and use it in GitHub Desktop.
Beautiful Streaming Filter, Map, and Collect using Channel Struct-wrapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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