Skip to content

Commit

Permalink
fn: add concurrent map operation for slices
Browse files Browse the repository at this point in the history
  • Loading branch information
ProofOfKeags committed Apr 15, 2024
1 parent 75b9b02 commit 41f6492
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions fn/slice.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package fn

import "sync"

// All returns true when the supplied predicate evaluates to true for all of
// the values in the slice.
func All[A any](pred func(A) bool, s []A) bool {
Expand Down Expand Up @@ -168,3 +170,21 @@ func ZipWith[A, B, C any](f func(A, B) C, a []A, b []B) []C {

return res
}

// ForEachConc maps the argument function over the slice, spawning a new
// goroutine for each element in the slice and then awaits all results before
// returning them.
func ForEachConc[A, B any](f func(A) B, as []A) []B {
wait := sync.WaitGroup{}
bs := make([]B, len(as))
for i, a := range as {
i, a := i, a
wait.Add(1)
go func() {
bs[i] = f(a)
wait.Done()
}()
}
wait.Wait()
return bs
}

0 comments on commit 41f6492

Please sign in to comment.