DEV Community

loading...

Use Recursion to Create a Range of Numbers

rthefounding profile image Randy Rivera ・1 min read

Here I provide you another opportunity to create a recursive function to solve a problem.

  • We have defined a function named rangeOfNumbers with two parameters. The function should return an array of integers which begins with a number represented by the startNum parameter and ends with a number represented by the endNum parameter. The starting number will always be less than or equal to the ending number. Your function must use recursion by calling itself and not use loops of any kind. It should also work for cases where both startNum and endNum are the same.
function rangeOfNumbers(startNum, endNum) {
  if (endNum == startNum) {
    return [endNum];
  } else {
    let arrayNum = rangeOfNumbers(startNum, endNum - 1)
    arrayNum.push(endNum);
    return arrayNum;
  }
}
Enter fullscreen mode Exit fullscreen mode
console.log(rangeOfNumbers(1, 5)); will display [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

Discussion (1)

Collapse
alfredosalzillo profile image
Alfredo Salzillo 🐺
function range(start, end, acc = []) {
   If (start === end) return [...acc, end]
   return range( start + 1, end, [...acc, start])
}
Enter fullscreen mode Exit fullscreen mode

In tail recursion is better. It's optimized by the JavaScript engine and will not fill the heap at any call, and will have the same space complexity of an iterative one.
And as a plus can be a one liner.

Forem Open with the Forem app