freeCodeCamp/curriculum/challenges/english/02-javascript-algorithms-an.../basic-javascript/use-recursion-to-create-a-c...

2.4 KiB

id title challengeType
5cd9a70215d3c4e65518328f Use Recursion to Create a Countdown 1

Description

Continuing from the previous challenge, we provide you another opportunity to create a recursive function to solve a problem.

Instructions

We have defined a function called countdown with two parameters. The function should take an array in the myArray parameter and append the numbers n through 1 based on the n parameter.
For example, calling this function with n = 5 will pad the array with the numbers [5, 4, 3, 2, 1] inside of it. Your function must use recursion by calling itself and must not use loops of any kind.

Tests

tests:
  - text: After calling <code>countdown(myArray, -1)</code>, myArray should be empty.
    testString: assert.isEmpty(padArray([], -1));
  - text: After calling <code>countdown(myArray, 10)</code>, myArray should contain <code>[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]</code>
    testString: assert.deepStrictEqual(padArray([], 10), [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]);
  - text: After calling <code>countdown(myArray, 5)</code>, myArray should contain <code>[5, 4, 3, 2, 1]</code>
    testString: assert.deepStrictEqual(padArray([], 5), [5, 4, 3, 2, 1]);
  - text: Your code should not rely on any kind of loops (<code>for</code> or <code>while</code> or higher order functions such as <code>forEach</code>, <code>map</code>, <code>filter</code>, or <code>reduce</code>.).
    testString: assert(!removeJSComments(code).match(/for|while|forEach|map|filter|reduce/g));
  - text: You should use recursion to solve this problem.
    testString: assert(removeJSComments(countdown.toString()).match(/countdown\s*\(.+\)\;/));

Challenge Seed



//Only change code below this line
function countdown(myArray, n){
  return;
}

After Test

const removeJSComments = str => str.replace(/\/\*[\s\S]*?\*\/|\/\/.*$/gm, '');
function padArray(arr, n){
  countdown(arr, n);
  return arr;
}

Solution

//Only change code below this line
function countdown(myArray, n){
  if(n <= 0){
    return;
  }
  else{
    myArray.push(n);
    countdown(myArray, n - 1);
  }
}