What is the Python range() type?
If you’re not familiar with Python, range()
refers to the use of the range type to create an immutable sequence of numbers.
“The range type represents an immutable sequence of numbers and is commonly used for looping a specific number of times in for loops.” — docs.python.org
The range()
constructor has two forms of definition:
range(stop)
range(start, stop[, step])
A concise explanation of the parameters, return value, etc. can be found on programiz.
A few examples:
Building the range() function in JavaScript
For simplicity sake, we will ignore the optional step
argument.
By using the Array
constructor, fill
and map
, you could work out a simple solution in a quick one-liner:
new Array(stop - start).fill(start).map((el, i) => el + i)
And maybe then offer a more complete solution, covering the case of calling range with only one argument:
But it’s not quite it yet. Can you see why this solution is wrong?
Remember, calling Python range
returns an immutable sequence of numbers. Notice how in order to get the familiar list data structure, the Python examples above wrap the return value of range with list()
.
An equal example in JavaScript should probably look something like this:
> Array.from(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
So how can we make a function in JavaScript return an “immutable sequence of numbers”? Is there any way to achieve the same structure of the range()
return value in JavaScript?
Iterators to the rescue!
Iterators are wildly used in different programming languages to allow us to iterate over different data structures.
“In JavaScript an iterator is an object which defines a sequence and potentially a return value upon its termination.” —developer.mozilla.org
Specifically in JavaScript, an iterator is any object which implements the Iterator protocol by having a next()
method that returns an object with two properties:
next() {
...
return {
value: // current value to be passed
done: // did we finish iterating over the data structure?
}
}
Using an iterator, you can provide your own logic on how to iterate. For example, here is a simple iterator that will skip every second item:
More importantly, If we create an object that defines [Symbol.iterator]
which returns that iterator, we can get exactly the behavior we were looking for:
Play around with these examples and see what kind of interesting and useful iterators you can create 💪.
By now you can probably imagine how we might approach creating Python range()
in JavaScript. This is how I implemented it:
As I mentioned, for simplicity's sake this implementation leaves out the step
argument from the original Python range()
, but it’s just a matter of extra logic that you can implement yourself. Feel free to @ me your solution ✌️.
Top comments (9)
You can significantly simplify by using a generator function, something like this:
You can also write custom functions for
map
,filter
,reduce
, etc. that will operate lazily on iterables:Laziness in action:
If you tried to do that with an array, you'd run out of memory.
Your code is really weird you mix iterator protocol with generators. You just can use this, it will do the same:
I've also written an article on higer order iterators including async but in Polish (you can use translate option to read it).
Generatory i Iteratory wyższego poziomu
Not weird at all, it's a common pattern. That way, you can easily extend your
range
objects with other properties, likemin
,max
,includes
, etc.More importantly, it also ensures you don't accidentally mutate the
range
and get unexpected results. With your version:With my version:
You can still get a mutable iterator from my version if you really need one, though. You just have to ask for it explicitly:
Hey lionel, thanks for the great feedback.
The idea of using generators looks really interesting. I'll look into it and maybe do a follow up article on Generators.
What you get with a generator function is basically what you hand-rolled with
return { value, done }
:They're pretty nifty 😊
Hey, thanks for sharing this @guyariely very timely, as I was just looking at JavaScript
range
and generator functions 🙂One question I have is what is the advantage of using an iterator here, rather than a simple
for n to n
and returning and array?I found this article (joshwcomeau.com/snippets/javascrip...) which uses a
for n
to generate the output, and seems to work just as well, and also, like @lukeshir mentioned, supportsforEach
because the return is an array.Link to a sandbox comparison: codesandbox.io/s/range-4idy5?file=...
Anyhow, thanks again for sharing!
Hey Daniel, The reason I used iterators was to match Python range structure.
Notice how in order to get the python list (or Array in JavaScript), you have to call list(). The same kind of structure and semantics can be achieved in JavaScript by using iterators.
I agree this isn't the greatest use case for iterators, but it's simple and opens up the door for further exploration of this great tool.
hey luke thanks for reading the article!
The reason I chose to use iterators is to match Python range() structure and semantics. I was looking to build a function / type that will only produce an array after calling Array.from() on the returned structure, similar to python list().
What's the difference b/w the above range function as opposed to this?