Skip to content

Commit

Permalink
stream support fold
Browse files Browse the repository at this point in the history
  • Loading branch information
azihsoyn committed Nov 10, 2016
1 parent 0fd2a3e commit 0021684
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
17 changes: 17 additions & 0 deletions examples/stream/fold/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package main

import (
"fmt"

"github.com/azihsoyn/gollection"
)

func main() {
arr := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

res, _ := gollection.NewStream(arr).Fold(100, func(v1, v2 int) int {
return v1 + v2
}).Result()
fmt.Println("origin : ", arr)
fmt.Println("ret : ", res)
}
47 changes: 47 additions & 0 deletions fold.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,14 @@ func (g *gollection) Fold(v0 interface{}, f interface{}) *gollection {
return &gollection{err: g.err}
}

if g.ch != nil {
return g.foldStream(v0, f)
}

return g.fold(v0, f)
}

func (g *gollection) fold(v0 interface{}, f interface{}) *gollection {
sv := reflect.ValueOf(g.slice)
if sv.Kind() != reflect.Slice {
return &gollection{
Expand Down Expand Up @@ -43,4 +51,43 @@ func (g *gollection) Fold(v0 interface{}, f interface{}) *gollection {
return &gollection{
val: ret,
}

}

func (g *gollection) foldStream(v0 interface{}, f interface{}) *gollection {
next := &gollection{
ch: make(chan interface{}),
}

funcValue := reflect.ValueOf(f)
funcType := funcValue.Type()
if funcType.Kind() != reflect.Func || funcType.NumIn() != 2 || funcType.NumOut() != 1 {
return &gollection{
slice: nil,
err: fmt.Errorf("gollection.Reduce called with invalid func. required func(in1, in2 <T>) out <T> but supplied %v", g.slice),
}
}

go func() {
ret := v0

for {
select {
case v, ok := <-g.ch:
if ok {
v1 := reflect.ValueOf(ret)
v2 := reflect.ValueOf(v)
ret = funcValue.Call([]reflect.Value{v1, v2})[0].Interface()
} else {
next.ch <- ret
close(next.ch)
return
}
default:
continue
}
}
}()
return next

}

0 comments on commit 0021684

Please sign in to comment.