Skip to content

Instantly share code, notes, and snippets.

@fbartho
Created June 6, 2018 01:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fbartho/250e873c464ec8da609d3008c964c6a5 to your computer and use it in GitHub Desktop.
Save fbartho/250e873c464ec8da609d3008c964c6a5 to your computer and use it in GitHub Desktop.
AsyncMap Experiments
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