31
loading...
This website collects cookies to deliver better user experience
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
range()
constructor has two forms of definition:range(stop)
range(start, stop[, step])
step
argument.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)
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()
.> Array.from(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
range()
return value in JavaScript?“In JavaScript an iterator is an object which defines a sequence and potentially a return value upon its termination.” —developer.mozilla.org
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?
}
}
[Symbol.iterator]
which returns that iterator, we can get exactly the behavior we were looking for:range()
in JavaScript. This is how I implemented it: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 ✌️.