In PHP, you can do...
range(1, 3); // Array(1, 2, 3)
range("A", "C"); // Array("A", "B", "C")
That is, there is a function that lets you get a range of numbers or characters by passing the upper and lower bounds.
Is there anything built-in to JavaScript natively for this? If not, how would I implement it?
I was surprised to come across this thread and see nothing like my solution (maybe I missed an answer), so here it is. I use a simple range function in ES6 syntax :
But it works only when counting forward (ie. begin < end), so we can modify it slightly when needed like so :
Here's my 2 cents:
Numbers
Character iteration
Iteration
As functions
As typed functions
lodash.js
_.range()
functionOld non es6 browsers without a library:
Thanks.
(ES6 credit to nils petersohn and other commenters)
You can use lodash or Undescore.js
range
:Alternatively, if you only need a consecutive range of integers you can do something like:
In ES6
range
can be implemented with generators:This implementation saves memory when iterating large sequences, because it doesn't have to materialize all values into an array:
Did some research on some various Range Functions. Checkout the jsperf comparison of the different ways to do these functions. Certainly not a perfect or exhaustive list, but should help :)
The Winner is...
Technically its not the fastest on firefox, but crazy speed difference (imho) on chrome makes up for it.
Also interesting observation is how much faster chrome is with these array functions than firefox. Chrome is at least 4 or 5 times faster.
Another version using ES6 generators ( see great Paolo Moretti answer with ES6 generators ):
Or, if we only need iterable, then: