@joepie91/range
v1.0.0
Published
Generates a range of numbers (optionally with step size) as an iterator with array methods
Readme
@joepie91/range
Generates an iterator containing all numbers in a specified range, optionally with a defined step size. The iterator also has (proxied) array methods, so that you can use methods like .map or .filter as if it were an array, without needing an explicit Array.from call. Negative step sizes are supported.
Warning: Using the array methods really uses the array methods. This means that the entire iterator is turned into an array, meaning all values are loaded into memory at once. If you want an iterator because you're working with very large ranges (millions of numbers), then don't use the array methods. This is an edge case, and the vast majority of people can use the array methods safely. If you're not sure whether this applies to you, it probably doesn't!
Usage
As an iterator:
const range = require("@joepie91/range");
/* Prints (each on a new line) the numbers 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 */
for (let i of range(0, 10)) {
console.log(i);
}
/* Prints (each on a new line) the numbers 0, 2, 4, 6, 8 */
for (let i of range(0, 10, 2)) {
console.log(i);
}
/* Prints (each on a new line) the numbers 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 */
for (let i of range(10, 0, -1)) {
console.log(i);
}As an array:
const range = require("@joepie91/range");
/* Prints (each on a new line) the numbers 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 */
range(0, 10).forEach((i) => {
console.log(i);
});
/* Prints (each on a new line) the numbers 0, 2, 4, 6, 8 */
range(0, 10, 2).forEach((i) => {
console.log(i);
});
/* Prints (each on a new line) the numbers 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 */
range(0, 10, -1).forEach((i) => {
console.log(i);
});
/* Or for example, using `.map`: */
let numbers = range(0, 10).map((i) => i * 10);
console.log(numbers); // [ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90 ]API
range(start, end, step = 1)
Generates and returns the iterator-with-array-methods.
- start: Required. The value to start at. This value is inclusive.
- end: Required. The value to end at. This value is exclusive,, ie. it isn't included in the sequence. Take a careful look at the negative-step examples above to see the implications for counting down, as it may be unintuitive!
- step: Optional, defaults to
1. The step size to increment with. Specify a negative step size to count down instead of up.
