Iterator Helpers reduce find some Short-Circuit
Wrap iterables with Iterator.from and terminate lazy pipelines via drop, find, some, every, and reduce so infinite or large streams stop on first match.
Code
let yielded = 0;
function* sequence() {
for (let n = 1; n <= 100; n++) {
yielded++;
yield n * 10;
}
}
// drop + find pulls only until the predicate matches once
const firstOver45 = Iterator.from(sequence())
.drop(2)
.find((val) => val > 45);
console.log('firstOver45:', firstOver45, '| yielded:', yielded);
// some short-circuits on a plain Set without building an intermediate array
const ports = new Set([80, 443, 8080, 8443]);
const hasHighPort = Iterator.from(ports).some((p) => p >= 8000);
const allPositive = Iterator.from(ports).every((p) => p > 0);
const totalPorts = Iterator.from(ports).reduce((sum, p) => sum + p, 0);
console.log('hasHighPort:', hasHighPort, '| allPositive:', allPositive, '| sum:', totalPorts);Output
Captured from a sandboxed run of this snippet in the build pipeline.
firstOver45: 50 | yielded: 5
hasHighPort: true | allPositive: true | sum: 17046Implementation flow — Iterator Helpers reduce find some Short-Circuit
The cycling part of this snippet is for (let n = 1; n <= 100; n++).
The file’s state is a handful of top-level bindings: yielded, firstOver45, ports, hasHighPort.
Points of care
- Nothing to vet in a supply-chain review — the file pulls in no packages.
Using it
The run emits 2 labeled sections — firstOver45:, hasHighPort: — one per step.
Key statements
const totalPorts = Iterator.from(ports).reduce((sum, p) => sum + p, 0);
const hasHighPort = Iterator.from(ports).some((p) => p >= 8000);
const allPositive = Iterator.from(ports).every((p) => p > 0);
Interactive Tools for This Topic
FAQ
- Can I paste this into a project as-is?
- Yes. Paste it in and run; no package manager step is needed. Its state lives in module-level bindings: `yielded`, `firstOver45`, `ports`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.