Range with Generator Function
Write a JavaScript generator function that takes a start and end value, yields each integer in that range, and returns the values as an array. Use the function* syntax with yield to produce values lazily.
Generator functions in JavaScript are defined with function* syntax and use the yield keyword to pause and resume execution. Each call to the generator's .next() method executes until the next yield statement, returning an object { value, done }. Generator functions can produce infinite sequences lazily because values are computed only when requested.
Generators are a powerful JavaScript feature for lazy evaluation, custom iteration, and managing asynchronous flow. They implement the iterator protocol (Symbol.iterator) and can be used with for-of loops and spread operators. The Array.from() method can consume a generator to produce an array: Array.from(gen()).
Time complexity is O(n) for consuming all yielded values, where n is the range size. Each yield pauses and resumes the generator function. Space complexity is O(1) for the generator state, O(n) for the collected array.
Edge cases include empty ranges (start >= end, generator yields nothing), single-element ranges, negative values, and ensuring the generator correctly handles the inclusive start and exclusive end convention.
Example Input & Output
Range 0 to 2
Empty range (start equals end)
Range 1 to 4
Three elements
Negative to positive
Algorithm Flow
Solution Approach
Create a generator function that yields a range of numbers using the function* syntax and yield keyword. Generators can pause and resume execution, producing a sequence of values lazily.
Calling a generator returns an iterator. Use for...of to consume values, or call next() manually. Generators are useful for lazy sequences and infinite lists.
Time O(1) per yield, Space O(1).
Best Answers
function* range(start, end) {
for (var i = start; i < end; i++) {
yield i;
}
}
function solution(start, end) {
return Array.from(range(start, end));
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
