Skip to content

Instantly share code, notes, and snippets.

@khanlou
Last active December 23, 2020 02:00
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save khanlou/a215d875e60af4f7dc1d64b12e4b004b to your computer and use it in GitHub Desktop.
Save khanlou/a215d875e60af4f7dc1d64b12e4b004b to your computer and use it in GitHub Desktop.
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