aboutsummaryrefslogtreecommitdiff
path: root/filter.go
diff options
context:
space:
mode:
authorAlexander Kiryukhin <a.kiryukhin@mail.ru>2022-04-07 21:36:40 +0300
committerAlexander Kiryukhin <a.kiryukhin@mail.ru>2022-04-07 21:36:40 +0300
commit9cd6b0fca87679e570fbdd4942e3068feb3439fa (patch)
tree557bf877d71854480f4171e9dd324cebb5606056 /filter.go
initial
Diffstat (limited to 'filter.go')
-rw-r--r--filter.go34
1 files changed, 34 insertions, 0 deletions
diff --git a/filter.go b/filter.go
new file mode 100644
index 0000000..20c23a9
--- /dev/null
+++ b/filter.go
@@ -0,0 +1,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
+}