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?
My new favorite form (ES2015)
And if you need a function with a
step
param:An interesting challenge would be to write the shortest function to do this. Recursion to the rescue!
Tends to be slow on large ranges, but luckily quantum computers are just around the corner.
An added bonus is that it's obfuscatory. Because we all know how important it is to hide our code from prying eyes.
To truly and utterly obfuscate the function, do this:
... more range, using a generator function.
Hope this is useful.
OK, in JavaScript we don't have a
range()
function like PHP, so we need to create the function which is quite easy thing, I write couple of one-line functions for you and separate them for Numbers and Alphabets as below:for Numbers:
and call it like:
for Alphabets:
and call it like:
Handy function to do the trick, run the code snippet below
here is how to use it
range (Start, End, Step=1, Offset=0);
range(5,10) // [5, 6, 7, 8, 9, 10]
range(10,5) // [10, 9, 8, 7, 6, 5]
range(10,2,2) // [10, 8, 6, 4, 2]
range(5,10,0,-1) // [6, 7, 8, 9] not 5,10 themselves
range(5,10,0,1) // [4, 5, 6, 7, 8, 9, 10, 11]
range(5,10,0,-2) // [7, 8]
range(10,0,2,2) // [12, 10, 8, 6, 4, 2, 0, -2]
hope you find it useful.
And here is how it works.
Basically I'm first calculating the length of the resulting array and create a zero filled array to that length, then fill it with the needed values
(step || 1)
=> And others like this means use the value ofstep
and if it was not provided use1
instead(Math.abs(end - start) + ((offset || 0) * 2)) / (step || 1) + 1)
to put it simpler (difference* offset in both direction/step)new Array(length).fill(0);
check here[0,0,0,..]
to the length we want. We map over it and return a new array with the values we need by usingArray.map(function() {})
var direction = start < end ? 1 : 0;
Obviously ifstart
is not smaller than theend
we need to move backward. I mean going from 0 to 5 or vice versastartingPoint
+stepSize
*index
will gives us the value we needYou can also do the following: