From 9a9508a22aa801919a108de1b1f409d08ec5a9ca Mon Sep 17 00:00:00 2001 From: Jordan Orelli Date: Mon, 22 Nov 2021 20:54:32 +0000 Subject: [PATCH] huh i wonderrrrr if this will work --- list/list.go | 27 +++++++++++++++++++++++++++ list/list_test.go | 1 + 2 files changed, 28 insertions(+) diff --git a/list/list.go b/list/list.go index e0ef1f1..3a8434b 100644 --- a/list/list.go +++ b/list/list.go @@ -2,6 +2,7 @@ package list import ( "strings" + "sync" "fmt" ) @@ -126,6 +127,32 @@ func (l List[T]) Map(f func(T) T) List[T] { 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 // returns a new list containing the values of the elements that passed the // predicate diff --git a/list/list_test.go b/list/list_test.go index 03c1340..54ac56a 100644 --- a/list/list_test.go +++ b/list/list_test.go @@ -105,6 +105,7 @@ func eq[T comparable](t *testing.T, expect T, found T) { func TestMap(t *testing.T) { nums := Make(2, 4, 6).Map(mult(5)) + t.Logf("Nums: %v", nums) eq(t, 10, nums.At(0)) eq(t, 20, nums.At(1)) eq(t, 30, nums.At(2))