Last active
December 23, 2020 02:00
-
-
Save khanlou/a215d875e60af4f7dc1d64b12e4b004b to your computer and use it in GitHub Desktop.
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