Created
September 1, 2019 09:11
-
-
Save wjlafrance/81b4a77fbc30975e3152591ef1144ee6 to your computer and use it in GitHub Desktop.
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
struct Fizzbuzz: Sequence, IteratorProtocol { | |
enum FizzbuzzValue: CustomDebugStringConvertible { | |
case fizz | |
case buzz | |
case fizzbuzz | |
case other(Int) | |
var debugDescription: String { | |
switch self { | |
case .fizz: return "Fizz" | |
case .buzz: return "Buzz" | |
case .fizzbuzz: return "FizzBuzz" | |
case let .other(value): return "\(value)" | |
} | |
} | |
} | |
typealias Element = FizzbuzzValue | |
let fizzDivisor: Int | |
let buzzDivisor: Int | |
var current = 1 | |
init(fizzDivisor: Int = 3, buzzDivisor: Int = 5) { | |
self.fizzDivisor = fizzDivisor | |
self.buzzDivisor = buzzDivisor | |
} | |
mutating func next() -> FizzbuzzValue? { | |
defer { current += 1 } | |
let isFizz = current % fizzDivisor == 0 | |
let isBuzz = current % buzzDivisor == 0 | |
if isFizz && isBuzz { return .fizzbuzz } | |
if isFizz { return .fizz } | |
if isBuzz { return .buzz } | |
return .other(current) | |
} | |
} | |
print(Fizzbuzz() | |
.prefix(100) | |
.map { "\($0)"} | |
.joined(separator: "\n")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment