huh i wonderrrrr if this will work

master
Jordan Orelli 3 years ago
parent ca6074e953
commit 9a9508a22a

@ -2,6 +2,7 @@ package list
import ( import (
"strings" "strings"
"sync"
"fmt" "fmt"
) )
@ -126,6 +127,32 @@ func (l List[T]) Map(f func(T) T) List[T] {
return mapped return mapped
} }
// Run is the same as Map, but is run concurrently. The function f will be run
// for every element of l in its own goroutine.
func Run[T any, Z any](l List[T], f func(T) Z) List[Z] {
var wg sync.WaitGroup
c := make(chan Z)
for n := l.head; n != nil; n = n.next {
wg.Add(1)
go func(v T) {
defer wg.Done()
c <- f(v)
}(n.val)
}
go func() {
wg.Wait()
close(c)
}()
var results List[Z]
for z := range c {
results.Push(z)
}
return results
}
// Filter applies a predicate function f to each element of the list and // Filter applies a predicate function f to each element of the list and
// returns a new list containing the values of the elements that passed the // returns a new list containing the values of the elements that passed the
// predicate // predicate

@ -105,6 +105,7 @@ func eq[T comparable](t *testing.T, expect T, found T) {
func TestMap(t *testing.T) { func TestMap(t *testing.T) {
nums := Make(2, 4, 6).Map(mult(5)) nums := Make(2, 4, 6).Map(mult(5))
t.Logf("Nums: %v", nums)
eq(t, 10, nums.At(0)) eq(t, 10, nums.At(0))
eq(t, 20, nums.At(1)) eq(t, 20, nums.At(1))
eq(t, 30, nums.At(2)) eq(t, 30, nums.At(2))

Loading…
Cancel
Save