Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
each_cons from Ruby in Swift as a function on Sequence
extension Collection {
func eachConsecutive(_ size: Int) -> Array<SubSequence> {
let droppedIndices = indices.dropFirst(size - 1)
return zip(indices, droppedIndices)
.map { return self[$0...$1] }
}
}
extension Sequence where SubSequence: Sequence, SubSequence.Iterator.Element == Iterator.Element {
typealias Pair = (Element, Element)
// you can do zip(self, self.dropFirst), but this slightly
// more complex version will work for single pass sequences as well
func eachPair() -> AnySequence<Pair> {
var iterator = self.makeIterator()
guard var previous = iterator.next() else { return AnySequence([]) }
return AnySequence({ () -> AnyIterator<Pair> in
return AnyIterator({
guard let next = iterator.next() else { return nil }
defer { previous = next }
return (previous, next)
})
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment