-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmap.go
56 lines (44 loc) · 1.08 KB
/
map.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package superlo
import (
"sync"
"golang.org/x/sync/errgroup"
)
// Map - returns a new collection of mapped values and error
func Map[T any, R any](collection []T, iteratee func(item T, index int) (R, error)) ([]R, error) {
result := make([]R, len(collection))
for i, item := range collection {
returnValue, err := iteratee(item, i)
if err != nil {
return nil, err
}
result[i] = returnValue
}
return result, nil
}
// ParallelMap - returns a new collection of mapped values and error
// `iteratee` is call in parallel. Result keep the same order.
func ParallelMap[T any, R any](collection []T, iteratee func(item T, index int) (R, error)) ([]R, error) {
result := make([]R, len(collection))
var (
eg errgroup.Group
mu sync.Mutex
)
for i, item := range collection {
func(_item T, _i int) {
eg.Go(func() error {
returnValue, err := iteratee(_item, _i)
if err != nil {
return err
}
mu.Lock()
result[_i] = returnValue
mu.Unlock()
return nil
})
}(item, i)
}
if err := eg.Wait(); err != nil {
return nil, err
}
return result, nil
}