Skip to content

Instantly share code, notes, and snippets.

@dabrahams
Created March 15, 2018 22:02
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 dabrahams/586d87e39f220323cb500eec761c2721 to your computer and use it in GitHub Desktop.
Save dabrahams/586d87e39f220323cb500eec761c2721 to your computer and use it in GitHub Desktop.
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