gitee.com/sy_183/go-common@v1.0.5-0.20231205030221-958cfe129b47/stream/iter/consumer.go (about)

     1  package iter
     2  
     3  import (
     4  	"gitee.com/sy_183/go-common/stream"
     5  )
     6  
     7  func ForEach[V any](action stream.Action[V], iter stream.Iter[V]) {
     8  	for {
     9  		if v, ok := iter(); ok {
    10  			action(v)
    11  		} else {
    12  			return
    13  		}
    14  	}
    15  }
    16  
    17  func Reduce[V, R any](reducer stream.Reducer[V, R], init R, iter stream.Iter[V]) R {
    18  	for {
    19  		if v, ok := iter(); ok {
    20  			init = reducer(init, v)
    21  		} else {
    22  			return init
    23  		}
    24  	}
    25  }
    26  
    27  func Collect[V any](iter stream.Iter[V]) (vs []V) {
    28  	for {
    29  		if v, ok := iter(); ok {
    30  			vs = append(vs, v)
    31  		} else {
    32  			return
    33  		}
    34  	}
    35  }
    36  
    37  func Count[V any](iter stream.Iter[V]) (count int) {
    38  	for {
    39  		if _, ok := iter(); ok {
    40  			count++
    41  		} else {
    42  			return
    43  		}
    44  	}
    45  }