Iterator.from Upgrades Plain Iterators Lazily
Wrap plain next() iterator objects with ES2025 Iterator.from so filter, map, and take chain lazily and stop pulling items once take hits its limit.
Code
let pulls = 0;
// Plain iterator object: implements .next() but does NOT inherit Iterator.prototype
const counterProtocol = {
next() {
pulls++;
if (pulls > 10) return { done: true, value: undefined };
return { done: false, value: pulls * 10 };
},
};
const picked = Iterator.from(counterProtocol)
.filter((n) => n % 20 === 0)
.map((n) => `item-${n}`)
.take(2)
.toArray();
console.log('picked:', JSON.stringify(picked));
// Lazy execution stops pulling from the underlying source as soon as take(2) is satisfied
console.log('total next() pulls:', pulls);Output
Captured from a sandboxed run of this snippet in the build pipeline.
picked: ["item-20","item-40"]
total next() pulls: 4Execution path — Iterator.from Upgrades Plain Iterators Lazily
Top-level bindings pulls, counterProtocol, picked hold the demo state — nothing sits inside a function scope.
The result comes back as an object carrying true.
What to watch for
- The environment needs no preparation beyond having the interpreter or compiler.
- The guard
pulls > 10terminates execution promptly through a leadingreturnwhen its condition holds.
Putting it to use
The file’s steps show up in the output as picked:, total next() pulls:.
The call returns true.
Core lines
if (pulls > 10) return { done: true, value: undefined };
return { done: false, value: pulls * 10 };
.map((n) => `item-${n}`)
.take(2)
.toArray();
FAQ
- Is anything beyond the standard library required?
- Nothing beyond the standard library — the snippet is dependency-free. Its state lives in module-level bindings: `pulls`, `counterProtocol`, `picked`.
- What does the code return?
- An object carrying `true`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.