Python Range Function In Javascript


Intro

While working on the Matching Quiz, I realized Javascript is missing one of my favorite Python functions: Range. For those who don't use Python, Range allows you to generate a list of numbers. It doesn't sound useful on the surface, but trust me it is. Note I will be using the term list and array interchangeably throughout this article. I'm lazy like that. In Python, range is often used to generate enumeration for loops. In my case I needed to generate a list of numbers in random order. This controls the sorting for the Matching Quiz. Now Python's Range function doesn't do randomization by default, it's something extra I added for my use case. So how do you use Range? It's simple, let's walk through the parameters.

Parameters

The start parameter is the lowest number in your generated set of numbers. For example if you're wanting a list of numbers from 1 to 10, you would specify 1 for the start parameter. Next is the stop parameter. This tells the script to stop generating numbers, however it is not included in the list of numbers. For example if you wanted a list of numbers from 1 - 10, you would have to specify 11 for the stop parameter. This behavior may seem odd at first, but this is how Python implements the function. Next is the step parameter. This parameter is optional. But this allows you to control how many steps between each number in the list. For example, say you want only odd numbers from 1 - 10 in your list. You would start with 1, stop with 11 and step with 2 (range(1, 11, 2)). The end result would be [1, 3, 5, 7, 9]. Pretty neat huh? Ok Matt, what's the random parameter? "randomize_order" is an optional bonus parameter I added for my use case. I needed the numbers to be returned in a random order. It defaults to false, so if you don't pass it. You'll end up with a standard list of numbers.

Usage Example

range(1, 11) //[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
range(1, 11, 2) //[1, 3, 5, 7, 9]

Code

        function range(start, stop, step = 1, randomize_order = false) {
            let arr = [];
            
            for(let i = start; i < stop; i += step) {
                arr.push(i);
            }
            
            if(randomize_order) arr = arr.sort(() => Math.random() - 0.5);
            
            return arr;
        }

Conclusion

Feel free to grab and use the code as you like. As always it's not our responsibility for damages (if they happen). Yotta yotta. But this is a great away to have the best of both worlds when switching back and forth between Python and Javascript.

Badges courtesy of shields.io & badges.pages.dev

  0

Categories: Programming

Tags: javascript, python