Created
March 15, 2018 22:02
-
-
Save dabrahams/586d87e39f220323cb500eec761c2721 to your computer and use it in GitHub Desktop.
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
public struct MyPrefixWhile<Base: Sequence> : Sequence { | |
var predicate: (Base.Element)->Bool | |
var base: Base | |
public struct Iterator : IteratorProtocol { | |
var predicate: (Base.Element)->Bool | |
var base: Base.Iterator? | |
public mutating func next() -> Base.Element? { | |
guard let r = base?.next() else { return nil } | |
if predicate(r) { return r } | |
base = nil | |
return nil | |
} | |
} | |
public func makeIterator() -> Iterator { | |
return Iterator(predicate: predicate, base: base.makeIterator()) | |
} | |
} | |
extension Sequence { | |
public func myPrefix( | |
while predicate: @escaping (Element) -> Bool | |
) -> MyPrefixWhile<Self> { | |
// Wrap it in AnySequence if you must | |
return MyPrefixWhile(predicate: predicate, base: self) | |
} | |
} | |
let positiveInts = sequence(first: 0) { $0 + 1 } | |
print(Array(positiveInts.myPrefix { $0 < 0 })) | |
print(Array(positiveInts.myPrefix { $0 < 10 })) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment