Last active
December 23, 2020 02:00
Collection chunking via @timvermeulen
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 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