Review this generated collector before it consumes a long-lived order source.
Collect at most a finite positive limit of approved order IDs from a possibly long single-pass iterable, stop without reading an extra item, and close the source when the limit ends consumption early.
JavaScript
function collectApproved(source, limit) {
const iterator = source[Symbol.iterator]();
const approved = [];
while (approved.length < limit) {
const { value } = iterator.next();
if (value === undefined) break;
if (value.status === 'approved') approved.push(value.id);
}
return approved;
}
function* readOrders(rows) {
try {
for (const row of rows) yield row;
} finally {
console.log('closed');
}
}
const rows = [{ id: 'A', status: 'approved' }];
console.log(collectApproved(readOrders(rows), 1));
generated code is illustrative, not from any one model