Oliver Jumpertz

Range

Category: JavaScript

Share this snippet to:

/**
* Creates an eager range, prefilled with values 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 {Array} An array containing all numbers from begin to endExclusive - 1
*/
function range(begin, endExclusive, step = 1) {
return Array.from(
{ length: (endExclusive - begin) / step },
(_, i) => begin + i * step
);
}

Usage

You usually want to use an eager range if you only have a finite amount of numbers to iterate. Next to that, you only want to use this eager range if your range is not too large and does not contain thousands of numbers.

range(0, 3).forEach((i) => console.log(i));
// prints 0, 1, 2 on the console
range(2, 10, 2).forEach((i) => console.log(i));
// prints 2, 4, 6, 8 on the console

Explanation

This range function just uses the Array.from factory method to create a new array.

The first parameter is a so-called Array-like object. It only needs a length property, which is used to calculate the resulting length of the array because you don’t want to waste too much space.

The second parameter is the so-called mapFn (map function). It is applied to each element of the Array on its creation. In this case, the map function runs over the array with its length, and uses the second parameter of the callback, the index, to calculate the next number at the desired position.

Performance

This function is fast enough, but the range it creates is still eager. Be careful when creating very large ranges. Those numbers will all take up memory, which can grow pretty large with this approach.

If you have large ranges, you might want to use a lazy range.


Share this snippet to: