Skip to content

Instantly share code, notes, and snippets.

@jakebromberg
Forked from khanlou/Array+EachCons.swift
Last active May 31, 2022 17:30
Show Gist options
  • Save jakebromberg/518fa414f2784528db57a003cefe26da to your computer and use it in GitHub Desktop.
Save jakebromberg/518fa414f2784528db57a003cefe26da 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() -> some Sequence where Element == Pair {
var iterator = self.makeIterator()
guard var previous = iterator.next() else {
return AnySequence<Pair> { EmptyIterator<Pair>() }
}
return AnySequence { () -> AnyIterator<Pair> in
AnyIterator {
guard let next = iterator.next() else { return nil }
defer { previous = next }
return (previous, next)
}
}
}
}
private struct EmptyIterator<Element>: IteratorProtocol {
func next() -> Element? { nil }
}
func test() {
let x = [1, 2, 3, 4]
for pair in x.eachPair() {
print(pair)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment