A JavaScript implementation of the Python's range() function.
Installation
npm i python-range
Examples
Basic usage
import range from 'python-range'; const r = range(10); console.log(r); // range(0, 10, 1) console.log(Array.from(r)); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] console.log(r[3]); // 3 console.log(r.length); // 10 console.log(Array.from(range(2, 5))); // [2, 3, 4] console.log(Array.from(range(5, 0, -1))); // [5, 4, 3, 2, 1]
Iteration
const r = range(3, 6); for (const n of r) { console.log(n); // logs 3, 4 and 5 } r.forEach(n => console.log(n)); // logs 3, 4, and 5
Lazy evaluation
Unlike other range modules, python-range has lazy evaluation.
See Why is “1000000000000000 in range(1000000000000001)” so fast in Python 3?
console.log(range(1000000000000001).includes(1000000000000000)); // true console.log(range(0, 100000000000001, 10).includes(100000000000000)); // true console.log(range(0, -1000000000, -3)[12345678]); // -37037034
Documentation
Exported values
python-range exports two values: a PythonRange class, and a range function (a default export), which returns a PythonRange object.
import range, {PythonRange} from 'python-range'; console.log(range(10) instanceof PythonRange); // true
new PythonRange(<int> start, <int> stop[, <int> step])
The PythonRange constructor creates a range starting with start (inclusive) and ending with stop (exclusive). The step parameter defaults to 1 and specifies the distance between two elements. The step parameter must be different than 0.
new PythonRange(<int> stop)
When called with only one argument, the start parameter defaults to 0 and the passed argument becomes stop.
const r = range(3); console.log(r.start); // 0 console.log(r.stop); // 3
Numeric properties
You can access range elements using array indices. Note that this requires native Proxy support.
const r = range(2, 5); console.log(r[0]); // 2 console.log(r[2]); // 4
start, stop and step properties
The PythonRange constructor creates these properties based on the arguments passed to the constructor, or the default values. These properties are writable, and changing them automatically updates the range.
const r = range(5); console.log(Array.from(r)); // [0, 1, 2, 3, 4] r.step = 2; console.log(Array.from(r)); // [0, 2, 4]
length property
The length property specifies the number of elements in the range. It's updated automatically when the start, stop and step properties are changed.
const r = range(5); console.log(r.length); // 5 r.stop = 3; console.log(r.length); // 3
PythonRange.prototype.get(<int> index)
Works the same as accessing numeric properties (e.g. r[2]). Use this method if you want to execute your code in environments without native Proxy support.
console.log(range(2, 5).get(1)); // 3