Instantly share code, notes, and snippets.

Embed
What would you like to do?
Collection chunking via @timvermeulen
extension Collection {
func chunk(size: IndexDistance) -> ChunkedCollection<Self> {
return ChunkedCollection(self, size: size)
}
}
struct ChunkedCollection<Base: Collection>: Collection {
private let base: Base
private let chunkSize: Base.IndexDistance
fileprivate init(_ base: Base, size: Base.IndexDistance) {
self.base = base
chunkSize = size
}
typealias Index = Base.Index
var startIndex: Index {
return base.startIndex
}
var endIndex: Index {
return base.endIndex
}
func index(after index: Index) -> Index {
return base.index(index, offsetBy: chunkSize, limitedBy: base.endIndex) ?? base.endIndex
}
subscript(index: Index) -> Base.SubSequence {
return base[index..<self.index(after: index)]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment