gitee.com/sy_183/go-common@v1.0.5-0.20231205030221-958cfe129b47/stream/ranger/consumer.go (about) 1 package ranger 2 3 import ( 4 "gitee.com/sy_183/go-common/stream" 5 ) 6 7 func ForEach[V any](ranger stream.Ranger[V], action stream.Action[V]) error { 8 return ranger(func(v V) error { 9 action(v) 10 return nil 11 }) 12 } 13 14 func Reduce[V, R any](ranger stream.Ranger[V], reducer stream.Reducer[V, R], init R) (R, error) { 15 err := ranger(func(v V) error { 16 init = reducer(init, v) 17 return nil 18 }) 19 return init, err 20 } 21 22 func Collect[V any](ranger stream.Ranger[V]) (vs []V, err error) { 23 err = ranger(func(v V) error { 24 vs = append(vs, v) 25 return nil 26 }) 27 return 28 } 29 30 func Append[V any](ranger stream.Ranger[V], vs []V) ([]V, error) { 31 err := ranger(func(v V) error { 32 vs = append(vs, v) 33 return nil 34 }) 35 return vs, err 36 } 37 38 func CollectSet[V comparable](ranger stream.Ranger[V]) (set map[V]struct{}, err error) { 39 err = ranger(func(v V) error { 40 if set == nil { 41 set = make(map[V]struct{}) 42 } 43 set[v] = struct{}{} 44 return nil 45 }) 46 return 47 } 48 49 func Count[V any](ranger stream.Ranger[V]) (i int, err error) { 50 err = ranger(func(v V) error { 51 i++ 52 return nil 53 }) 54 return 55 }