Created
September 13, 2023 00:20
-
-
Save maxjustus/121ee0c841542d17e1c11c8de8fc2d09 to your computer and use it in GitHub Desktop.
golang parallelMap
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func parallelMap[T any, V any](input []T, f func(T) (V, error)) ([]V, error) { | |
outChan := make(chan V, len(input)) | |
errChan := make(chan error, len(input)) | |
for i, val := range input { | |
go func(i int, val T) { | |
out, err := f(val) | |
if err != nil { | |
errChan <- err | |
} else { | |
outChan <- out | |
} | |
}(i, val) | |
} | |
output := make([]V, len(input)) | |
for i := 0; i < len(input); i++ { | |
select { | |
case out := <-outChan: | |
output[i] = out | |
case err := <-errChan: | |
return []V{}, err | |
} | |
} | |
return output, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment