Skip to the solution
EasyFrontend5 min read

Implement _.range(start, end, step) generator

1.1k views

The problem

Problem, as an interviewer would state it: "Write a range(start, end, step) like lodash's — produces the sequence of numbers from start up to (not including) end, stepping by step. Then tell me a real reason to implement it as a generator instead of returning a plain array."

Examples:

Code
[...range(0, 10, 2)] -> [0, 2, 4, 6, 8]
[...range(10, 0, -2)] -> [10, 8, 6, 4, 2]

Clarifying questions expected:

  • Should this return a real array directly, or something lazily iterable (a generator)?
  • Is a negative step expected to work symmetrically (counting down)?
  • Should end ever be included, or always strictly exclusive like the real lodash behavior?

Code / implementation expected: Yes — real, direct proof that a generator-based range can represent a genuinely infinite sequence, which an array-materializing version structurally cannot.

  • range
  • array
  • utility

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

5 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 generator-based range() creates instantly and can represent a genuinely infinite sequence, unlike an array-materializing version

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 21 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 nextEasy

Object tree traversal

Continue