Last active
July 7, 2020 17:48
-
-
Save khanlou/f27b34f28b21b4834a758913e06a5f3b 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() -> 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