Adam Schork
Adam Schork

Reputation: 29

How to Create an Array using Recursion While Specifying the Min & Max Values in JavaScript

Here is the challenge:

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) {

}
rangeOfNumbers(5, 10); //Should return [5, 6, 7, 8, 9, 10]

Is there a simple, one line way of tackling this? I'm struggling with how to handle the base case and return the desired array with recursion.

Upvotes: 1

Views: 1450

Answers (2)

Guest
Guest

Reputation: 21

Here's another way using spread syntax -

const range = (a, b) =>
  a > b
    ? []
    : [ a, ...range(a + 1, b) ]
    
console.log(range(1, 5))
// [ 1, 2, 3, 4, 5 ]

console.log(range(3, 6))
// [ 3, 4, 5, 6 ]

console.log(range(9, 3))
// []

Upvotes: 2

Colin
Colin

Reputation: 1215

function rangeOfNumbers(startNum, endNum) {
  return startNum <= endNum ? [startNum].concat(rangeOfNumbers(startNum+1, endNum)) : []
}
console.log(rangeOfNumbers(5, 10));

Upvotes: 4

Related Questions