We've explored the core concepts of recursion: the base case and the recursive step. Now, let's solidify our understanding by tackling a practical, real-world problem that can be elegantly solved using recursion. Imagine you're a librarian trying to organize a massive collection of books. Each book might be part of a series, and within that series, there might be sub-series. Your goal is to create a complete, flattened list of all book titles, regardless of how nested they are within their series.
Let's represent our book collection using a data structure. A book can either be a standalone item or a container for other books (representing a series or sub-series). This nested structure is a perfect candidate for recursion.
const bookCollection = [
{ title: 'The Hitchhiker\'s Guide to the Galaxy' },
{
title: 'The Lord of the Rings',
series: [
{ title: 'The Fellowship of the Ring' },
{
title: 'The Two Towers',
series: [
{ title: 'Book A in Sub-series' },
{ title: 'Book B in Sub-series' }
]
},
{ title: 'The Return of the King' }
]
},
{ title: 'Pride and Prejudice' }
];Our objective is to create a function, let's call it flattenBookList, that takes this bookCollection and returns a simple array of all book titles. We need to traverse this nested structure and extract every single title.
Here's how we can approach this recursively. The function will iterate through the current collection of books. For each book:
- If the book has a
titleproperty, we add it to our result list. - If the book also has a
seriesproperty (which is an array of other books), we need to recursively callflattenBookListon thisseriesarray and add its results to our main list. This is the essence of the recursive step – breaking down a complex problem (flattening a nested list) into smaller, identical sub-problems (flattening a sub-series).
The base case in this scenario is implicit. When a book has no series property, or when the series array is empty, the recursion for that branch naturally stops, as there are no further sub-problems to solve. The function then returns the collected titles from that level.