Number.range()
proposal for ECMAScript in currently on stage-1
and if it makes to stage-4
(I strongly hope it will) one day we would be able to use Number.range()
and BigInt.range
in Javascript.
Currently in JavaScript, if we were to be implement range
we would:
const range = (start, end) => [...Array(end - start + 1)].map((_, indx) => start + indx);
Or use generators, many other ways or ended up libs like lodash, ramda or likes.
With this proposal we could do something like:
[...Number.range(1, 100, 2)] // odd number from 1 to 99
[...Number.range(0, 5, { step: 1.75 })];
//[0, 1.75, 3.5]
[...Number.range(5, -6, -1)]
(11) [5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5]
So, it is basically: Number.range(start, end, option)
We can also use it with the iterator helper proposal.
Number.range(0, Infinity)
.take(10)
.filter(x => !(x % 2))
.toArray();
// [0, 2, 4, 6, 8]
Similarly with BigInt.range
[...BigInt.range(-2n, 3n)]
// [-2n, -1n, 0n, 1n, 2n]
Hope you liked this proposal by Jack Works, feel free to provide your feedback as this on Stage-1 as of today.
Top comments (6)
I'd suggest the best way to do range today would be:
No need to double memory and processing by spreading the result into an array or making another one with map.
For most purposes, an iterator is actually preferable. These can be created via generators, as mentioned in the article.
I wrote one in an older article of mine:
dev.to/emnudge/generating-arrays-i...
Yup, that is covered in the many other ways of doing this link.
Nice proposal, I didn't know about this one! Thanks for sharing!
Just the usual jerk, there is a little typo in the link to "may other ways"
Hah hah, thanks, fixed it!
I don't want to be negative, but... honestly, I've been a full time developer for the last 15 years and I needed such a function no more than 10 times. Is it really so useful?