Question presented to candidate: "Given an infinite generator, say one that produces natural numbers forever, how would you compute the first 3 even squares greater than some threshold using the built-in Iterator helper methods, without ever materializing an array of every number up to that point? Walk through why chaining .map().filter().take() on the raw generator does not blow up memory or hang forever, unlike calling Array.from() on it would."
What a strong answer should cover:
Iterator.prototypenow has built-in helper methods —.map,.filter,.take,.drop,.flatMap,.reduce,.toArray,.forEach,.some,.every,.find— available directly on any iterator, including generator objects, without needing a library.- These methods are genuinely LAZY: chaining
.map().filter()builds a pipeline description but pulls nothing from the underlying source until something actually consumes the result, like.toArray(), afor...ofloop, or another terminal method. .take(n)and.drop(n)are what make working with an infinite source safe —.take(n)stops pulling oncenvalues have been produced, so a chain ending in.take(3).toArray()on an infinite generator genuinely terminates.Iterator.from(iterableOrIterator)wraps a plain iterable (like an array's default iterator) so it also gets access to the helper methods, since plain arrays do not have.map/.filterin this lazy iterator sense already (their own.map/.filterare eager, array-producing methods).- Calling
Array.from()(or spreading with[...iterator]) on an infinite iterator, by contrast, tries to pull every value and never returns — it is not lazy at all. - Short-circuiting terminal methods like
.find()also only pull as many values as needed to find a match, not the entire sequence.
Clarifying questions expected:
- "Does the target runtime actually support Iterator helpers natively, or does this need a polyfill?" — a real, practical compatibility question given how recently this landed.
- "Should the pipeline be reusable across multiple consumptions, or is a single pass acceptable?" — iterators are inherently single-pass/stateful, unlike arrays, which is worth naming explicitly.
Code / implementation expected: Yes — a runnable pipeline over an infinite generator, plus a real, counted proof that only the minimum necessary number of values was ever pulled from the source.