- vừa được xem lúc

Blog#83: Introduction to the Recursion Pattern in JavaScript

0 0 7

Người đăng: NGUYỄN ANH TUẤN

Theo Viblo Asia

Hi, I'm Tuan, a Full-stack Web Developer from Tokyo 😊. Follow my blog to not miss out on useful and interesting articles in the future.

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."

Functional programming is a programming paradigm (a way of organizing code) that emphasizes the use of functions. In functional programming, it is common to use recursion to solve problems.

Examples

Here are five examples of real-world problems that can be solved using the recursion pattern in JavaScript with functional-oriented programming:

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 JavaScript with functional-oriented 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 of real-world problems that can be solved using the recursion pattern. By understanding and mastering the recursion pattern, you can become a more effective and efficient programmer.

As always, I hope you enjoyed this article and learned something new. Thank you and see you in the next articles!

If you liked this article, please give me a like and subscribe to support me. Thank you. 😊

Ref

Bình luận

Bài viết tương tự

- vừa được xem lúc

Giới thiệu Typescript - Sự khác nhau giữa Typescript và Javascript

Typescript là gì. TypeScript là một ngôn ngữ giúp cung cấp quy mô lớn hơn so với JavaScript.

0 0 500

- vừa được xem lúc

Bạn đã biết các tips này khi làm việc với chuỗi trong JavaScript chưa ?

Hi xin chào các bạn, tiếp tục chuỗi chủ đề về cái thằng JavaScript này, hôm nay mình sẽ giới thiệu cho các bạn một số thủ thuật hay ho khi làm việc với chuỗi trong JavaScript có thể bạn đã hoặc chưa từng dùng. Cụ thể như nào thì hãy cùng mình tìm hiểu trong bài viết này nhé (go).

0 0 414

- vừa được xem lúc

Một số phương thức với object trong Javascript

Trong Javascript có hỗ trợ các loại dữ liệu cơ bản là giống với hầu hết những ngôn ngữ lập trình khác. Bài viết này mình sẽ giới thiệu về Object và một số phương thức thường dùng với nó.

0 0 136

- vừa được xem lúc

Tìm hiểu về thư viện axios

Giới thiệu. Axios là gì? Axios là một thư viện HTTP Client dựa trên Promise.

0 0 117

- vừa được xem lúc

Imports và Exports trong JavaScript ES6

. Giới thiệu. ES6 cung cấp cho chúng ta import (nhập), export (xuất) các functions, biến từ module này sang module khác và sử dụng nó trong các file khác.

0 0 93

- vừa được xem lúc

Bài toán đọc số thành chữ (phần 2) - Hoàn chỉnh chương trình dưới 100 dòng code

Tiếp tục bài viết còn dang dở ở phần trước Phân tích bài toán đọc số thành chữ (phần 1) - Phân tích đề và những mảnh ghép đầu tiên. Bạn nào chưa đọc thì có thể xem ở link trên trước nhé.

0 0 229