Skip to content

Instantly share code, notes, and snippets.

@lukaskollmer
Last active June 23, 2025 07:44
Show Gist options
  • Save lukaskollmer/c0c3e165037dcae2f045c0994e51dca4 to your computer and use it in GitHub Desktop.
Save lukaskollmer/c0c3e165037dcae2f045c0994e51dca4 to your computer and use it in GitHub Desktop.
private struct AdjacentTripletsIterator<Base: Collection>: IteratorProtocol {
typealias Element = (Base.Element, Base.Element, Base.Element)
private var baseIt: Base.Iterator
private var nextResult: Element?
init(base: Base) {
self.baseIt = base.makeIterator()
if let elem1 = baseIt.next(), let elem2 = baseIt.next(), let elem3 = baseIt.next() {
nextResult = (elem1, elem2, elem3)
}
}
mutating func next() -> Element? {
guard let result = nextResult else {
return nil
}
if let nextElem = baseIt.next() {
nextResult = (result.1, result.2, nextElem)
} else {
nextResult = nil
}
return result
}
}
extension Collection {
func adjacentTriplets() -> some Collection<(Element, Element, Element)> {
AdjacentTripletsIterator(base: self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment