Skip to the solution
MediumDSAAsked in 20246 min read

Implement a Range Class Using the Iterator Protocol Manually (No Generator Functions Allowed)

514 views

The problem

Problem, as an interviewer would state it: "Implement a Range class that can be used in for...of, spread and destructuring, by implementing the iterator protocol by hand. No generator functions."

Examples:

Code
[...new Range(0, 10, 3)];               // [0, 3, 6, 9]
for (const x of new Range(5, 0, -2)) {} // 5, 3, 1

Clarifying questions expected:

  • Is the end exclusive, and are negative steps supported?
  • Should a range be iterable more than once, and should it support an infinite end?
  • What should happen for a step of zero, and what about fractional steps?

Code / implementation expected: Yes — real, direct proof the object works with every consumer of the iterable protocol, including early exit.

  • 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

6 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 hand-written iterator Range works with every consumer, supports an infinite end, avoids float drift, and reports exactly when return() is called

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 113 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 nextMedium

Build a Deterministic Feature-Flag Bucketing Function (Consistent Hash-Based A/B Assignment)

Continue