Skip to content

Instantly share code, notes, and snippets.

@khanlou
Last active July 7, 2020 17:48
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save khanlou/f27b34f28b21b4834a758913e06a5f3b to your computer and use it in GitHub Desktop.
Save khanlou/f27b34f28b21b4834a758913e06a5f3b to your computer and use it in GitHub Desktop.
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 {
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