Skip to content

Instantly share code, notes, and snippets.

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