how to find the range of any given integer by a specified step with recursion

Issue

I want to use recursion to find the range of a given integer by a specified step.

  given number --> -20 
  step --> 4
  returns --> [ -20, -16, -12, -8, -4, -2, 0, 2, 4 ]

Thus far, I was able to create a recursive function to return the corresponding results:

function range(num,step,res=[]) {
  const s = num < step ? step : -step; 
  if (num === step + s) return res;
  return num === step ? [...res,num] : range(num+s,step,[...res,num]);
}

console.log(range(5,1)); // [ 5, 4, 3, 2, 1 ]
console.log(range(-8,2)); // [ -8, -6, -4, -2, 0, 2 ]
console.log(range(-20,4)); // [ -20, -16, -12, -8, -4, -2, 0, 2, 4 ]

However, the following invocations returns stackoverflow

console.log(range(-7,2)); // stackoverflow!
console.log(range(11,5)); // stackoverflow!

I know something is wrong with the code, but I just couldn’t figure out what it is. Can someone kindly point me in the right direction or show me what I’m doing wrong. Million thanks in advance 🙂

UPDATE:

Thanks to TazHinkle’s control flow I was able to solve the problem as follow:

function range(num,step,res=[]) {
  const s = num < step ? step : -step;
  if (num > step && num < step) return res;
  if (num < step && num + s > step) return [...res,num];
  return num === step ? [...res,num] : range(num+s,step,[...res,num]);
}

console.log(range(5,1)); // [ 5, 4, 3, 2, 1 ]
console.log(range(-8,2)); // [ -8, -6, -4, -2, 0, 2 ]
console.log(range(-20,4)); // [ -20, -16, -12, -8, -4, 0, 4 ]
console.log(range(11,5)); // [ 11, 6, 1 ]
console.log(range(-7,2)); // [ -7, -3, -5, -1, 1 ]
console.log(range(-9,4)); // [ -9, -5, -1, 3 ]

Solution

The case range(-7,2) cannot resolve in the current version because it will infinitely step between 1 and 3 (because it’s stepping by 2 and trying to arrive at 2, but it’s never going to).
You can make it give up when it goes past with something like this:

function range(num,step,res=[]) {
    const s = num < step ? step : -step;
    const forward = num < step ? true : false;
    if (num === step + s) return res;
    if(forward) {
        if(num + s > step) {
            return [...res,num]
        }
        return num === step ? [...res,num] : range(num+s,step,[...res,num]);
    }else {
        if(num + s < step) {
            return [...res,num]
        }
        return num === step ? [...res,num] : range(num+s,step,[...res,num]);
    }
}

Answered By – TazHinkle

Answer Checked By – Mary Flores (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.