+7

Introduction to the Recursion Pattern in JavaScript

In programming, recursion is when a function calls itself. This can be useful for solving problems that can be divided into smaller, similar problems. The process of breaking down a problem into smaller pieces is called "divide and conquer."

Examples

Here are five examples that can be solved using the recursion pattern in JavaScript:

Calculating the Factorial of a Number

The factorial of a number is the product of all the numbers from 1 to that number. For example, the factorial of 5 (written as 5!) is 1 * 2 * 3 * 4 * 5 = 120. Here is a recursive function that calculates the factorial of a number:

function factorial(n) {
  if (n === 1) return 1;
  return n * factorial(n - 1);
}

Flattening an Array

Sometimes, you may have an array that contains other arrays as elements. You can use recursion to flatten the array and return a new array with all the elements in a single level. Here is a recursive function that flattens an array:

function flattenArray(arr) {
  let flatArray = [];
  for (let i = 0; i < arr.length; i++) {
    if (Array.isArray(arr[i])) {
      flatArray = flatArray.concat(flattenArray(arr[i]));
    } else {
      flatArray.push(arr[i]);
    }
  }
  return flatArray;
}

Finding an Element in an Array

You can use recursion to search for an element in an array. Here is a recursive function that searches for an element in an array and returns its index if found, or -1 if not found:

function findElement(arr, element) {
  if (arr.length === 0) return -1;
  if (arr[0] === element) return 0;
  let index = findElement(arr.slice(1), element);
  if (index === -1) return -1;
  return index + 1;
}

Reversing a String

You can use recursion to reverse a string by breaking it down into smaller strings and concatenating them in the opposite order. Here is a recursive function that reverses a string:

function reverseString(str) {
  if (str.length === 0) return "";
  return reverseString(str.slice(1)) + str[0];
}

Generating the Fibonacci Sequence

The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. You can use recursion to generate the Fibonacci sequence. Here is a recursive function that generates the Fibonacci sequence:

function fibonacci(n) {
  if (n <= 1) return n;
  return fibonacci(n - 1) + fibonacci(n - 2);
}

Conclusion

The recursion pattern is a powerful technique for solving problems in programming. It allows you to break down a problem into smaller, similar problems and solve them recursively. In this article, we looked at five examples that can be solved using the recursion pattern. By understanding and mastering the recursion pattern, you can become a more effective and efficient programmer.

Mình hy vọng bạn thích bài viết này và học thêm được điều gì đó mới.

Donate mình một ly cafe hoặc 1 cây bút bi để mình có thêm động lực cho ra nhiều bài viết hay và chất lượng hơn trong tương lai nhé. À mà nếu bạn có bất kỳ câu hỏi nào thì đừng ngại comment hoặc liên hệ mình qua: Zalo - 0374226770 hoặc Facebook. Mình xin cảm ơn.

Momo: NGUYỄN ANH TUẤN - 0374226770

TPBank: NGUYỄN ANH TUẤN - 0374226770 (hoặc 01681423001)

image.png


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí