Flatten nested comment replies up to a maxLevel depth

In this problem, you will flatten nested comments into a single list, a classic use of recursion. You are given a data structure representing a list of posts and their nested replies. Each post is represented as an object with the following properties:
id (number): A unique identifier for the post or comment.text (string): The content of the post or comment.replyTo (number, optional): The id of the post or comment this is replying to.replies (array): An array of child comments (can be empty).Your task is to write a React function that flattens this nested tree into a single-level list (array), including only the posts and comments up to a specified depth maxLevel. If maxLevel = 1, return the top-level posts and their direct replies. If maxLevel = 2, include one more level of replies, and so on. Replies deeper than maxLevel should not be included in the flattened result.
maxLevel and returns a flat array of nodes up to the required depth.posts: Array<Post>
maxLevel: number
Array<Post> // flattened to the required depth
Input:
posts = [
{
"id": 1,
"text": "This is a post 1",
"replies": [
{
"id": 2,
"replyTo": 1,
"text": "This is a comment, child to post 1",
"replies": [
{
"id": 3,
"replyTo": 2,
"text": "This is a comment, child to comment 2",
"replies": []
}
]
},
{
"id": 4,
"replyTo": 1,
"text": "This is a comment, child to post 1",
"replies": []
}
]
},
{
"id": 5,
"text": "This is a post 2",
"replies": []
}
]
maxLevel = 1
Output:
[
{ id: 1, text: "This is a post 1" },
{ id: 2, replyTo: 1, text: "This is a comment, child to post 1" },
{ id: 4, replyTo: 1, text: "This is a comment, child to post 1" },
{ id: 5, text: "This is a post 2" }
]
Explanation:
- Level 0: Post 1 and Post 2 are included.
- Level 1: Direct replies to Post 1 (id 2, id 4) are included.
- Level 2: id 3 is a reply to id 2, but since maxLevel = 1, it is not included.
id, text, and (optional) replies.maxLevel depth (e.g., 1 = top-level + direct replies).