Created
June 20, 2021 03:18
-
-
Save AndrewBarba/89c81ab1e98626e29c728eccd9cf1219 to your computer and use it in GitHub Desktop.
Concurrent async version of map on any Sequence
This file contains 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
extension Sequence { | |
func mapAsync<T>(_ handler: @escaping (Element) async -> T) async -> [T] { | |
return await withTaskGroup(of: (Int, T).self) { group in | |
var results: [Int: T] = [:] | |
for (index, item) in self.enumerated() { | |
group.async { (index, await handler(item)) } | |
} | |
for await (index, transformed) in group { | |
results[index] = transformed | |
} | |
return self.enumerated().map { index, _ in results[index]! } | |
} | |
} | |
} |
Author
AndrewBarba
commented
Jun 20, 2021
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment