Skip to content

Instantly share code, notes, and snippets.

@astrokin
Created March 23, 2018 08:05
Show Gist options
  • Save astrokin/88674a1d905612e3c0b0b834e38da198 to your computer and use it in GitHub Desktop.
Save astrokin/88674a1d905612e3c0b0b834e38da198 to your computer and use it in GitHub Desktop.
concurrentMap
final class ThreadSafe<A> {
private var _value: A
private let queue = DispatchQueue(label: "ThreadSafe")
init(_ value: A) {
self._value = value
}
var value: A {
return queue.sync { _value }
}
func atomically(_ transform: (inout A) -> ()) {
queue.sync {
transform(&self._value)
}
}
}
extension Array {
func concurrentMap<B>(_ transform: @escaping (Element) -> B) -> [B] {
let result = ThreadSafe(Array<B?>(repeating: nil, count: count))
DispatchQueue.concurrentPerform(iterations: count) { idx in
let element = self[idx]
let transformed = transform(element)
result.atomically {
$0[idx] = transformed
}
}
return result.value.map { $0! }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment