Created
September 19, 2020 07:57
-
-
Save stephanmantler/805e1ec493b98f50d86a27f27e2a84de to your computer and use it in GitHub Desktop.
Functional Swift FizzBuzz
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
extension Array where Element == Int { | |
func fizzBuzz() -> [String] { | |
return self.map(evalBuilder(pickers: [fibui(3, "Fizz"), fibui(5, "Buzz"), fibui(7, "Humm")])) | |
} | |
private func fibui(_ mult: Int, _ out: String) -> ((Int)->String?) { | |
return { (number: Int) in number.isMultiple(of: mult) ? out : nil } | |
} | |
private func evalBuilder(pickers:[(Int)->String?]) -> ((Int)->String) { | |
return { (number: Int) in | |
let output = pickers.compactMap { f in return f(number) } | |
return output.isEmpty ? "\(number)" : output.joined() | |
} | |
} | |
} | |
let array = Array(1...20) | |
print(array.fizzBuzz()) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment