Created
June 6, 2018 01:22
-
-
Save fbartho/250e873c464ec8da609d3008c964c6a5 to your computer and use it in GitHub Desktop.
AsyncMap Experiments
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
let arr = [1, 2, 3, 4, 5] | |
print("test") | |
func someAsyncAPI(_ entry: Int, completion: @escaping (Int) -> Void) { | |
let sleepTime = max(0,3-entry) | |
DispatchQueue.global().asyncAfter(deadline: .now() + 0.1 * Double(sleepTime)) { | |
completion(entry * -1); | |
} | |
} | |
func map<T,U>(_ array: [T], transform: (T, @escaping (U) -> Void) -> (), withCompletionHandler handler: @escaping ([U]) -> Void) { | |
print("initiating map \(array)") | |
var remaining = array.count; | |
var results: [U?] = Array(repeating: nil, count: remaining) | |
let semaphore = DispatchSemaphore(value: 1) | |
array.enumerated().forEach { index, entry in | |
print("Initiating \(entry)") | |
transform(entry, {(outputValue: U) in | |
semaphore.wait() | |
results[index] = outputValue | |
remaining -= 1; | |
let done = remaining == 0 | |
semaphore.signal() | |
if (done) { | |
DispatchQueue.main.async { | |
handler(results) | |
} | |
} | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment