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 l
Handy function to do the trick, run the code snippet below
function range(start, end, step, offset) {
var len = (Math.abs(end - start) + ((offset || 0) * 2)) / (step || 1) + 1;
var direction = start < end ? 1 : -1;
var startingPoint = start - (direction * (offset || 0));
var stepSize = direction * (step || 1);
return Array(len).fill(0).map(function(_, index) {
return startingPoint + (stepSize * index);
});
}
console.log('range(1, 5)=> ' + range(1, 5));
console.log('range(5, 1)=> ' + range(5, 1));
console.log('range(5, 5)=> ' + range(5, 5));
console.log('range(-5, 5)=> ' + range(-5, 5));
console.log('range(-10, 5, 5)=> ' + range(-10, 5, 5));
console.log('range(1, 5, 1, 2)=> ' + range(1, 5, 1, 2));
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 of step
and if it was not provided use 1
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 using Array.map(function() {})
var direction = start < end ? 1 : 0;
Obviously if start
is not smaller than the end
we need to move backward. I mean going from 0 to 5 or vice versastartingPoint
+ stepSize
* index
will gives us the value we need