Tackling recursion (not just) in Typescript


Recursion is a fundamental programming concept that refers to a function calling itself. It can be a powerful tool for solving problems, but it can also be a source of confusion and frustration, especially for beginners. In this tutorial, we'll explore how to use recursion effectively in TypeScript, a popular superset of JavaScript that adds optional static typing and other features.

One important thing to keep in mind when working with recursion is to define a base case, which is a condition that stops the function from calling itself again. Without a base case, the function will keep calling itself indefinitely, leading to an infinite loop.

Tackling recursion in TypeScript involves understanding how to use recursive functions effectively in a TypeScript program. This includes defining a base case to stop the function from calling itself indefinitely, considering the performance of recursive functions, and potentially using techniques such as memoization and tail call optimization to improve the performance of the function. It also involves understanding the specific syntax and features of TypeScript, such as optional static typing and compiler flags, that can be used in recursive functions.

Steps to use Recursion in TypeScript

In addition to understanding how to use recursion effectively in TypeScript, there are a few other things to consider when tackling recursion in your TypeScript programs −

  • Choose the right tool for the job − Recursion can be powerful, but there may be better solutions to a problem. Consider whether an iterative (loop-based) solution or another approach might be more appropriate.

  • Test your code thoroughly − Recursive functions can be challenging to debug, so it's essential to test your code to ensure it works correctly.

  • Understand the limitations of recursion − Recursive functions can consume a significant amount of memory for large inputs due to creating new stack frames for each function call. Stack overflow mistakes could result from this.

  • Use recursion sparingly − While recursion can be a helpful tool, it's essential to use it sparingly and only when it's the most appropriate solution to a problem.

By keeping these things in mind, you can effectively tackle using recursion in your TypeScript programs.

Example 1

Here is an example of how to tackle recursion in TypeScript. To tackle recursion in this example, we start by defining the base case that stops the function from calling itself indefinitely. In this case, the base case is when n is 0 or 1. We then define the recursive case when n is greater than one and specify how the function should calculate the nth number in the Fibonacci sequence. The Fibonacci function accepts a single argument n and returns a number. The function uses a base case to return 0 or 1 when n is 0 or 1, respectively. In the recursive case, the function returns the sum of the (n - 1)th and (n - 2)th numbers in the Fibonacci sequence.

Finally, we test the function with different input values to ensure it works correctly. By following these steps, we can effectively tackle the use of recursion in this TypeScript function.

// function that calculates the nth number in the Fibonacci sequence
function fibonacci(n: number): number {
   // the base case: when n is 0 or 1, return n
   if (n === 0 || n === 1) {
      return n
   }
   // In the recursive case, calculate the nth number by adding the
   // (n - 1)th and (n - 2)th numbers in the sequence
   return fibonacci(n - 1) + fibonacci(n - 2)
}

// Examine the function using various input values
console.log('Fibonacci of 0th term: ', fibonacci(0)) // 0
console.log('Fibonacci of 1st term: ', fibonacci(1)) // 1
console.log('Fibonacci of 5th term: ', fibonacci(5)) // 5
console.log('Fibonacci of 10th term: ', fibonacci(10)) // 55

On compiling, it will generate the following JavaScript code −

// function that calculates the nth number in the Fibonacci sequence
function fibonacci(n) {

   // the base case: when n is 0 or 1, return n
   if (n === 0 || n === 1) {
      return n;
   }
   
   // In the recursive case, calculate the nth number by adding the
   
   // (n - 1)th and (n - 2)th numbers in the sequence
   return fibonacci(n - 1) + fibonacci(n - 2);
}

// Examine the function using various input values
console.log('Fibonacci of 0th term: ', fibonacci(0)); // 0
console.log('Fibonacci of 1st term: ', fibonacci(1)); // 1
console.log('Fibonacci of 5th term: ', fibonacci(5)); // 5
console.log('Fibonacci of 10th term: ', fibonacci(10)); // 55

Output

The above code will produce the following output −

Fibonacci of 0th term:  0
Fibonacci of 1st term:  1
Fibonacci of 5th term:  5
Fibonacci of 10th term:  55

Example 2

To tackle recursion in this example, we start by defining the base case that stops the function from calling itself indefinitely. In this case, the base case is when the array is empty. We then describe the recursive case when the array is not empty and specify how the function should calculate the sum of the array elements. The sum function accepts an array of numbers and returns a number. The function uses a base case to return 0 when the array is empty. In the recursive case, the function returns the first element in the array plus the sum of the remaining elements.

Finally, we test the function with different input values to ensure it works correctly. By following these steps, we can effectively tackle the use of recursion in this TypeScript function.

// function that calculates the sum of all numbers in an array
function sum(arr: number[]): number {

   // the base case: when the array is empty, return 0
   if (arr.length === 0) {
      return 0
   }
   
   // In the recursive case, return the first element in the array plus the sum
   
   // of the remaining elements
   return arr[0] + sum(arr.slice(1))
}

// Test the function with different input values
console.log('Sum of array [1, 2, 3, 4, 5]: ', sum([1, 2, 3, 4, 5])) // 15
console.log('Sum of array [-1, 2, -3, 4, -5]: ', sum([-1, 2, -3, 4, -5])) // -3
console.log('Sum of array []: ', sum([])) // 0

On compiling, it will generate the following JavaScript code −

// function that calculates the sum of all numbers in an array
function sum(arr) {

   // the base case: when the array is empty, return 0
   if (arr.length === 0) {
      return 0;
   }
   
   // In the recursive case, return the first element in the array plus the sum
   
   // of the remaining elements
   return arr[0] + sum(arr.slice(1));
}

// Test the function with different input values
console.log('Sum of array [1, 2, 3, 4, 5]: ', sum([1, 2, 3, 4, 5])); // 15
console.log('Sum of array [-1, 2, -3, 4, -5]: ', sum([-1, 2, -3, 4, -5])); // -3
console.log('Sum of array []: ', sum([])); // 0

Output

The above code will produce the following output −

Sum of array [1, 2, 3, 4, 5]:  15
Sum of array [-1, 2, -3, 4, -5]:  -3
Sum of array []:  0

Updated on: 20-Jan-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements