Created
May 23, 2023 14:20
-
-
Save TsRebornz/b6afb3a2d3e4fb6d04f23084015b1041 to your computer and use it in GitHub Desktop.
MessageDecoder
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
import Foundation | |
final class MessagePrinter { | |
private let decoder = MessageDecoder() | |
func printEncodedMessage(_ encodedMessage: [Int]) { | |
decoder.decodeMessage(encodedMessage) { message in | |
self.printDecodedMessage(message) | |
} | |
} | |
private func printDecodedMessage(_ message: String) { | |
print("Decoded message is:") | |
print(message) | |
} | |
} | |
final class MessageDecoder { | |
func decodeMessage(_ encodedMessage: [Int], completion: @escaping (String) -> Void) { | |
/// Task: | |
/// | |
/// decode message asynchronously | |
/// using provided internal implementation | |
let group = DispatchGroup() | |
var preResult = [(index: Int, result: String)]() | |
encodedMessage.enumerated().forEach { currentIndex, mapIndex in | |
group.enter() | |
decodePhrase(at: mapIndex) { value in | |
let tuple = (index: currentIndex, result: value) | |
preResult.append(tuple) | |
group.leave() | |
} | |
} | |
group.notify(queue: DispatchQueue.main) { | |
let result: String = preResult.sorted(by: { $0.index < $1.index }) | |
.reduce("", { | |
return $0 + $1.result | |
}) | |
completion(result) | |
} | |
} | |
private static let phrases = ["problem.", "First,", "the", "solve", "Then,", "code.", "the", "write"] | |
private func decodePhrase(at index: Int, completion: @escaping (String) -> Void) { | |
let delay = Double.random(in: 0..<2) | |
DispatchQueue.global().asyncAfter(deadline: .now() + delay) { | |
let phrase = Self.phrases[index] | |
DispatchQueue.main.async { | |
completion(phrase) | |
} | |
} | |
} | |
} | |
MessagePrinter().printEncodedMessage([1, 3, 2, 0, 4, 7, 6, 5]) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment