Skip to the solution
HardFrontendAsked in 20247 min read

Create lazy evaluator

2.3k views

The problem

Problem, as an interviewer would state it: "Build a lazy evaluation pipeline supporting .map(), .filter(), and .take(n) over a real, potentially INFINITE sequence — transformations should only actually run on values that are genuinely consumed."

Examples:

Code
lazySeq(infiniteNumbers()).map(n => n*2).filter(n => n%3===0).take(3); // works, despite the infinite source

Clarifying questions expected:

  • Does this genuinely need to support an infinite source, or would a large-but-finite array be sufficient to demonstrate laziness?
  • Should chained .map()/.filter() calls compose into ONE pass over the source, or process the whole source once per operation?
  • Is there a real risk of an infinite loop if .take(n) is never reached (e.g., a filter that never matches)?

Code / implementation expected: Yes — real, direct proof against a genuinely infinite generator, counting real transformation calls to confirm the pipeline never eagerly processes more than strictly necessary.

  • js-coding
  • utility
  • algorithm

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

7 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: a lazy map/filter/take pipeline over a genuinely infinite generator makes only 9 real map() calls, never processing the whole sequence

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 136 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextHard

Throttled API poll client

Continue