it looks like your method to determine your step is a little bit off.
lets first look at how to determine a proper step.
Here is our test range:
[1,3,6,10,15].
The differences between the numbers is [2,3,4,5] we can represent the differences as : x + 1, x + 2, x + 3, x + 4. so we can combine these into 4x + 10. This is our total number incremented and it equals our stop - start (15 - 1) which is 14.
so our revised equation is 14 = 4x + 10 which when solved gives us x = 1;
4 here represents the number of steps, and 10 is the sum of the number of steps.
we can use carl gauss's formula to determine the sum.
the formula is (n / 2)(first number + last number) = sum
here n is the number of steps. and in our equation the number of steps will always be len - 1. While the last number will always be 1.
so our translated gauss' formula is (len - 1) / 2 * (len - 1 + 1)
we then plug that into our formula to determine the step:
step =
(Math.abs(stop - start) - (len - 1)/2 * (len - 1 + 1))/(len - 1)
SKIP TO HERE IF YOU AREN'T INTERESTED IN THE MATH TO FIND THE STEP
Alright. Now that we correctly found the step. lets see some code.
function ranger(start = 0, stop = 0, len = 1) {
let incArray = [];
let step = (Math.abs(stop - start) - (len - 1)/2*(len - 1 + 1))/(len - 1);
console.log('step is', step);
if(start < stop){
for(var i = 0, currentValue = start; currentValue < stop; i++){
//use default value on our first iteration of the loop
if(i> 0){
//we are grabbing the previous item in the array and adding
//the step plus i to it
//for ranger(1, 15, 5)) when i = 1, step = 1, incArray[1], so
// current value = 1 + 1 + 1 = 3;
currentValue = (i + step + incArray[incArray.length -1])
}
incArray.push(currentValue)
}
}
else{
for(var i = len, currentValue = start; currentValue > stop; i--){
if(i< len ){
currentValue = (-(i + step) + incArray[incArray.length -1])
}
incArray.push(currentValue)
prevValue = currentValue;
}
}
return incArray;
}
console.log('asc', ranger(1, 15, 5));
console.log('asc', ranger(1, 21, 6));
console.log('desc', ranger(15, 1, 5));
//now try a range with a step of 2:
console.log('asc', ranger(1, 19, 5));
// asc (5) [1, 3, 6, 10, 15]
// desc (5) [15, 10, 6, 3, 1]
This is just a rough draft, so you can cleanly refactor with map, and make it work more dynamically for ascending and descending.