DEV Community is a community of 615,790 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Number.range; Stage-1 proposal

hemanth.hm Updated on ・1 min read

`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.

Discussion (6)

Mike Talbot • Edited

I'd suggest the best way to do range today would be:

``````    const range = (start, end)=>Array.from({length: end-start}, (__,i)=>start+i)
``````

No need to double memory and processing by spreading the result into an array or making another one with map.

EmNudge

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...

``````class Range {
constructor(min, max, step = 1) {
this.val = min;
this.end = max;
this.step = step;
}

* [Symbol.iterator]() {
while (this.val <= this.end) {
yield this.val;
this.val += this.step;
}
}
}
``````
hemanth.hm

Yup, that is covered in the many other ways of doing this link.

Keff