Created
December 5, 2018 23:51
-
-
Save IanKeen/477dae744ab2697e76ecee1a74277b56 to your computer and use it in GitHub Desktop.
BatchedSequence
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
import Foundation | |
/// A sequence whose elements are emitted in batches of the specified size | |
struct BatchedSequence<Base: Sequence>: Sequence { | |
private let size: Int | |
private let base: Base | |
init(base: Base, size: Int) { | |
self.size = size | |
self.base = base | |
} | |
func makeIterator() -> AnyIterator<[Base.Element]> { | |
var iterator = base.makeIterator() | |
var current: [Base.Element] = [] | |
return .init { | |
while current.count < self.size, let value = iterator.next() { | |
current.append(value) | |
} | |
defer { current = [] } | |
return current.isEmpty ? nil : current | |
} | |
} | |
} | |
extension Sequence { | |
/// Return `self` as a `BatchedSequence` | |
/// | |
/// - Parameter size: The maximum size of batches to create | |
/// - Returns: A `Sequence` whose elements are batches of elements from `self` | |
func batched(by size: Int) -> BatchedSequence<Self> { | |
return BatchedSequence(base: self, size: size) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment