Recursion challenge - Edabit

Viewed 107

The problem wants me to output the string "Edabit" with the number of "a" characters equaling the initial number passed through the function.

I have tried different methods of concatenation but for some reason the string of "a"s seem to ignore their place in the concatenation.

function howManyTimes(num) {
    let str = ''
    
    if (num === 0){
        return `Ed${str}bit`
    }
    else {
        str += 'a'
        return str += howManyTimes(num - 1)
    }
}

console.assert(howManyTimes(0) == "Edbit", "1. Instead got "+howManyTimes(0));
console.assert(howManyTimes(1) == "Edabit", "2. Instead got "+howManyTimes(1));
console.assert(howManyTimes(10) == "Edaaaaaaaaaabit", "3. Instead got "+howManyTimes(10));

2 Answers

function howManyTimes(num, str) {
  if (!str) str = '';
  
  if (num > 0) {
    return howManyTimes(num - 1, str + 'a');
  } else {
    return `Ed${str}bit`;
  }
}

console.log(howManyTimes(8));

One issue is that your recursion is always appending the result of the method to an a. Rather than doing that, pass along the aggregated string to then be used once you reach the end.

You can always separate out the part that can use straightforward recursion from a shell that calls that part and does something with the result. For instance,

const nAs = (n) =>
  n == 0 ? '' : nAs (n - 1) + 'a'

const howManyTimes = (n) =>
  `Ed${nAs (n)}bit`

console .log (howManyTimes (0))
console .log (howManyTimes (1))
console .log (howManyTimes (10))

Of course I would only write it this way in a recursion challenge. For this example, there are more straightforward ways to write this, including const howManyTimes = (n) => `Ed${'a'.repeat(n)}bit`

Related