Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
extension SequenceType {
func prefixWhile(condition: Generator.Element -> Bool) -> [Generator.Element] {
var g = self.generate()
return Array( anyGenerator {
if let n = g.next() where condition(n) {
return n
} else {
return nil
}
} )
}
func drop(n: Int) -> [Generator.Element]{
var g = self.generate()
for _ in 0..<n { g.next() }
return Array(AnySequence{g})
}
func jump(n: Int) -> [Generator.Element] {
var g = self.generate()
return Array( anyGenerator {
for _ in 0..<n {g.next()}
return g.next()
} )
}
func hop(n: Int) -> [Generator.Element] {
var g = self.generate()
return Array( anyGenerator {
defer { for _ in 0..<n {g.next()} }
return g.next()
} )
}
func frame (n: Int) -> AnyGenerator<ArraySlice<Generator.Element>> {
var (g, count) = (self.generate(), 0)
var window: ArraySlice<Generator.Element>? = ArraySlice(anyGenerator{++count > n ? nil : g.next()})
return anyGenerator {
defer { window = g.next().map{ dropFirst(window!) + [$0] } }
return window
}
}
}
func zipWithPadding <
S0: SequenceType, S1: SequenceType, E0, E1 where
S0.Generator.Element == E0, S1.Generator.Element == E1
> (s0: S0, s1: S1) -> AnyGenerator<(E0?, E1?)> {
var (g0, g1) :
(S0.Generator?, S1.Generator?) =
(s0.generate(), s1.generate())
return anyGenerator {
let e0: E0? = g0?.next()
let e1: E1? = g1?.next()
if e0 == nil { g0 = nil }
if e1 == nil { g1 = nil }
return (e0 != nil || e1 != nil) ? (e0, e1) : nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.