for (let i = 0; i < 10; i += 2) {
// Whatever
}
I mean, come on. It's 2023! Why do we still have to write code like that?
Python, for e.g., has its awesome range()
function which returns an iterable sequence of numbers within the provided range. Rust also has a range operator (0..10
) that does the same thing.
JS too could really use a range operator.
One that would return a new special Range
iterable which could be looped over like
for (let i of :10:2) {
// Whatever
}
Isn't that cool? A few examples for you to catch the semantics
1:10 // 1, 2, 3, ..., 9
:10 // 0, 1, 2, ..., 9
10: // 10, 11, 12, ..., Infinity
: // 0, 1, 2, ..., Infinity
:10:2 // 0, 2, 4, ..., 9
1:10: // 1, 2, 3, ..., 9
::2 // 0, 2, 4, ..., Infinity
:: // You know this
Very like Python's array slice notation.
Speaking of arrays, it's also quite common to need an array with an arithmetic sequence of numbers. Maybe we could 'magically spread' the Range
iterable into an array for that?
const numbers = [...1:10] // [1, 2, 3, ..., 9]
That's two birds with one stone. What do u think?