github.com/songzhibin97/go-baseutils@v0.0.2-0.20240302024150-487d8ce9c082/app/bconcurrent/map_reduce.go (about)

     1  package bconcurrent
     2  
     3  func MapChan[T any](in <-chan T, fn func(T) T) <-chan T {
     4  	out := make(chan T, 1)
     5  	if in == nil {
     6  		close(out)
     7  		return out
     8  	}
     9  	go func() {
    10  		defer close(out)
    11  		for v := range in {
    12  			out <- fn(v)
    13  		}
    14  	}()
    15  	return out
    16  }
    17  
    18  func ReduceChan[T any](in <-chan T, fn func(r, v T) T) T {
    19  	if in == nil {
    20  		var zero T
    21  		return zero
    22  	}
    23  	out := <-in
    24  	for v := range in {
    25  		out = fn(out, v)
    26  	}
    27  	return out
    28  }