Javascript Function to Generate an Array of Numbers within a Specified Range (the Range Function)


The Range Function in Javascript

Let’s review the following JavaScript function called range. This function generates an array of numbers within a specified range, with a default step of 1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const range = (from, to, step = 1) => {
    if (typeof from !== 'number' || typeof to !== 'number' || typeof step !== 'number') {
        throw new TypeError('All arguments must be numbers');
    }
    if (from > to) {
        throw new RangeError('The start of the range cannot be greater than the end');
    }
    if (step <= 0) {
        throw new RangeError('Step must be a positive number');
    }
    
    let i = from;
    const rng = [];
    while (i <= to) {
        rng.push(i);
        i += step;
    }
    return rng;
}
const range = (from, to, step = 1) => {
    if (typeof from !== 'number' || typeof to !== 'number' || typeof step !== 'number') {
        throw new TypeError('All arguments must be numbers');
    }
    if (from > to) {
        throw new RangeError('The start of the range cannot be greater than the end');
    }
    if (step <= 0) {
        throw new RangeError('Step must be a positive number');
    }
    
    let i = from;
    const rng = [];
    while (i <= to) {
        rng.push(i);
        i += step;
    }
    return rng;
}

Functionality

The range function takes three parameters: from, to, and step. from and to specify the range’s boundaries, while step indicates the increment between each number in the array. The function’s default step is 1. The function works by initializing a variable i with the from value, then iteratively pushing i into an array and increasing i by step until i exceeds to. The function then returns the generated array.

Usefulness

The range function can be useful in various scenarios where you need to create an array of numbers within a certain range. For example, you might use it in a for-loop as an alternative to using an index variable.

Correctness

The range function appears to be correct and should function as expected. It checks whether i is within the range from and to, correctly increments i by step, and pushes i to the array. And it includes error handling to ensure correct use, making it more reliable. We also add some type checking or error handling to ensure that the inputs are numbers and that from is less than or equal to to, and step is a positive number. This would make the function more robust against unexpected input.

Performance

The performance of this function is linear, as it loops through the numbers from from to to, making it O(n). This is the expected performance for this type of operation. However, keep in mind that if you’re dealing with very large ranges, it may lead to a performance bottleneck or even exceed the maximum array size in JavaScript.

Generator/Iterator

in JavaScript, you can return an iterator from a function. An iterator is an object that provides a next method which returns the next item in a sequence. This concept is part of the iterator protocol in JavaScript.

Let’s take the range function as an example and adapt it to return an iterator:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function range(from, to, step = 1) {
    let current = from;
 
    return {
        next() {
            if (current > to) {
                return { done: true }; // signals that iteration is complete
            }
 
            let value = current;
            current += step;
            
            return { value, done: false }; // provides next value
        }
    };
}
 
let numbers = range(1, 5);
 
for (let num of numbers) {
    console.log(num); // 1, 2, 3, 4, 5
}
function range(from, to, step = 1) {
    let current = from;

    return {
        next() {
            if (current > to) {
                return { done: true }; // signals that iteration is complete
            }

            let value = current;
            current += step;
            
            return { value, done: false }; // provides next value
        }
    };
}

let numbers = range(1, 5);

for (let num of numbers) {
    console.log(num); // 1, 2, 3, 4, 5
}

This example uses the iterator protocol to generate a sequence of numbers. However, if you directly use the range iterator in a for-of loop, it will throw an error because for-of loops in JavaScript actually rely on the iterable protocol, which in turn uses the iterator protocol.

To make it work, we need to provide a [Symbol.iterator] method, which is part of the iterable protocol and should return an iterator:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
function range(from, to, step = 1) {
    return {
        [Symbol.iterator]() {
            let current = from;
 
            return {
                next() {
                    if (current > to) {
                        return { done: true };
                    }
 
                    let value = current;
                    current += step;
 
                    return { value, done: false };
                }
            };
        }
    };
}
 
let numbers = range(1, 5);
 
for (let num of numbers) {
    console.log(num); // 1, 2, 3, 4, 5
}
function range(from, to, step = 1) {
    return {
        [Symbol.iterator]() {
            let current = from;

            return {
                next() {
                    if (current > to) {
                        return { done: true };
                    }

                    let value = current;
                    current += step;

                    return { value, done: false };
                }
            };
        }
    };
}

let numbers = range(1, 5);

for (let num of numbers) {
    console.log(num); // 1, 2, 3, 4, 5
}

Now the range function returns an iterable object that can be used directly in a for-of loop, a spread operator, and other JavaScript constructs that expect an iterable.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
825 words
Last Post: APIM: Azure Managed API - Difference Between External vs Internal Mode
Next Post: What is LLVM? (Low-Level Virtual Machine)

The Permanent URL is: Javascript Function to Generate an Array of Numbers within a Specified Range (the Range Function)

Leave a Reply