TransWikia.com

Recursively appending to an array with ternary operator not working

Stack Overflow Asked by Michael Nascimento on December 30, 2021

I’m trying to create a recursive function that returns an array of interger in a range of numbers.

If I use a ternary operator, the base case returns ‘undefined’. I can’t see where is the problem.

Using JSLint I get this message: "Wrap a ternary expression in parens, with a line break after the left paren."

The code:

function rangeOfNumbers(startNum, endNum) {
  return startNum === endNum
    ? startNum
    : rangeOfNumbers(startNum, endNum - 1).concat(endNum);
}

One Answer

In your original example, you were just returning startNum which is a number. Instead, we want to return an array containing the startNum so we can concatenate that value when returned.

Try this:

function rangeOfNumbers(startNum, endNum) {
  return startNum === endNum
    ? [startNum]
    : rangeOfNumbers(startNum, endNum - 1).concat(endNum);
}

Answered by rhigdon on December 30, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP