Oliver Jumpertz

Lazy Range

Category: JavaScript

Share this snippet to:

/**
* Creates a lazy range, from begin to endExclusive - 1.
*
* @param {number} begin - The start of the range
* @param {number} exclusive - The exclusive upper bound of the range
* @param {number} [step=1] - The step size. Defaults to 1
* @returns {number} - Always yields the next number in the range
*/
function* range(begin, endExclusive, step = 1) {
let current = begin;
while (current < endExclusive) {
yield current;
current += step;
}
}

Usage

You want to use a lazy range if you have large ranges with many numbers inside it. By this, you reduce the memory overhead drastically.

for (const value of range(0, 5)) {
console.log(value);
}
// prints 0, 1, 2, 4, 5 to the console
for (const value of range(0, 10, 2)) {
console.log(value);
}
// prints 0, 2, 4, 6, 8 to the console

Explanation

This range function uses a generator function. Generator functions are special because they can save their state and return (yield) multiple times. In this case, the generator always yields the next number, and after that, it increments this number and returns that incremented number the next time you call the generator.

In this case, the generator is called whenever the for..of loop executes the next time.

Performance

This function is fast because generators are fast enough. Thanks to the gnerator, you won’t need to care too much about memory consumption.


Share this snippet to: