Defined Concurrency

Created Diff never expires
4 removals
24 lines
21 additions
41 lines
import "sync"
import (
"runtime"
"sync"
)

var _concurrency = runtime.NumCPU()

func MaxConcurrency(concurrency int) {
_concurrency = concurrency
}


// Map manipulates a slice and transforms it to a slice of another type.
// Map manipulates a slice and transforms it to a slice of another type.
// `iteratee` is call in parallel. Result keep the same order.
// `iteratee` is call in parallel. Result keep the same order.
func Map[T any, R any](collection []T, iteratee func(T, int) R) []R {
func Map[T any, R any](collection []T, iteratee func(T, int) R) []R {
result := make([]R, len(collection))
result := make([]R, len(collection))


c := _concurrency
if c <= 0 {
c = len(collection)
}
routines := make(chan struct{}, c)

var wg sync.WaitGroup
var wg sync.WaitGroup
wg.Add(len(collection))


for i, item := range collection {
for i, item := range collection {
wg.Add(1)
go func(_item T, _i int) {
go func(_item T, _i int) {
defer wg.Done()

routines <- struct{}{}
res := iteratee(_item, _i)
res := iteratee(_item, _i)
<-routines


result[_i] = res
result[_i] = res

wg.Done()
}(item, i)
}(item, i)
}
}


wg.Wait()
wg.Wait()


return result
return result
}
}