-
-
Save jakebromberg/518fa414f2784528db57a003cefe26da to your computer and use it in GitHub Desktop.
each_cons from Ruby in Swift as a function on Sequence
This file contains 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
extension Collection { | |
func eachConsecutive(_ size: Int) -> Array<SubSequence> { | |
let droppedIndices = indices.dropFirst(size - 1) | |
return zip(indices, droppedIndices) | |
.map { return self[$0...$1] } | |
} | |
} |
This file contains 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
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 } | |
} |
This file contains 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
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