Last active
June 23, 2025 07:44
-
-
Save lukaskollmer/c0c3e165037dcae2f045c0994e51dca4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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