blob: 20c23a9cf6dddd9cb8dc98abfa9ce70069317ffb (
plain) (
blame)
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
|
package collection
import "sync"
func FilterSync[T any](collection []T, filter func(item T, idx int) bool) []T {
var result []T
for i, v := range collection {
if filter(v, i) {
result = append(result, v)
}
}
return result
}
func Filter[T any](collection []T, filter func(item T, idx int) bool) []T {
var result []T
mu := sync.Mutex{}
wg := sync.WaitGroup{}
wg.Add(len(collection))
for i, v := range collection {
func(v T, i int) {
go func() {
defer wg.Done()
if filter(v, i) {
mu.Lock()
result = append(result, v)
mu.Unlock()
}
}()
}(v, i)
}
wg.Wait()
return result
}
|