skip to Main Content

We have defined a function called countdown with one parameter (n). The function should use recursion to return an array containing the integers n through 1 based on the n parameter. If the function is called with a number less than 1, the function should return an empty array. For example, calling this function with n = 5 should return the array [5, 4, 3, 2, 1]. Your function must use recursion by calling itself and must not use loops of any kind.

function countdown(n){
    if (n < 1){
        return [];
    }else{
        const countArray = countdown(n - 1);
        countArray.push(n);
        return countArray;
    }
 }

I am getting the following errors:
countdown(10) should return [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] countdown(5) should return [5, 4, 3, 2, 1] Global variables should not be used to cache the array.

3

Answers


  1. You could use an optional argument to pass the result array into the recursive calls:

    function countdown(n, arr = []){
      return n < 1 ? arr : arr.push(n) && countdown(n - 1, arr);
    }
    
    console.log(...countdown(10));
     

    The spread is slooooow:

    enter image description here

    <script benchmark data-count="1000">
    
    const count=1000;
    
    // @benchmark spread/iterator
    {
      function countdown(n) {
          const arr = [n];
          if( n > 1) arr.push( ...countdown(n-1));
          return arr;
      }
      countdown(count);
    }
    
    // @benchmark recursion
    {
      function countdown(n, arr = []){
        return n < 1 ? arr : arr.push(n) && countdown(n - 1, arr);
      }
      countdown(count);
    }
    
    </script>
    <script src="https://cdn.jsdelivr.net/gh/silentmantra/benchmark/loader.js"></script>
    Login or Signup to reply.
  2. This works using the spread operator.

    function countdown(n) {
        const arr = [n];
        if( n > 1) arr.push( ...countdown(n-1));
        return arr;
    }
    
    Login or Signup to reply.
  3. There are many possible ways of going about this… here is just one:

    Here: I’ve used the following:

    function countdown(n) {
      if (n < 1) {
        return []
      } else {
        return [n, ...countdown(n - 1)]
      }
    }
    console.log(countdown(5));

    The spread operator unpacks elements of iterable objects such as arrays, sets, and maps into a list.
    So the line

      return [n, ...countdown(n - 1)]
    

    If we step through an example like countdown(2) it would look like this:

      // n = 2
      return [2, ...countdown(1)]
      // countdown(1) evaluates to [1]
      // meaning it looks like:
      // return [2, ...[1]]
      // which is: [2, 1]
    
      // n = 1
      return [1, ...countdown(0)]
      // countdown(0) evaluates to []
      // meaning it looks like:
      // return [1, ...[]]
      // which is: [1] (because `[]` is empty)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search