Here is the basic tree structure I am working with:
class Group {
id: ObjectId;
name: string;
subGroups: [ObjectId]
}
https://i.sstatic.net/woZFs.jpg
For instance, Group A contains Group B and C as subGroups, while Group C has subGroups F, G, H, and so on.
I am in need of implementing an algorithm to recursively fetch all groups:
Expected Output = [Group A, Group B, Group C, Group D, Group E, Group F, Group G, Group H, Group I, Group J]
However, I require fetching the subGroups asynchronously from the database using async/await.
Approach 1
const tr = async (group: Group, result: Group[]) => {
console.log(group);
result.push(group);
for (const id of group.subGroups) {
const groupId = id.toHexString();
const subGroup = this.findGroup(groupId);
tr(await subGroup, result);
}
};
const result = [];
await tr(user.group, result);
console.log(result);
Approach 2
async transverse(group: Group, result: Group[]) {
console.log(group);
result.push(group);
for (const id of group.subGroups) {
const groupId = id.toHexString();
const subGroup = await this.findGroup(groupId);
await this.transverse(subGroup, result);
}
}
const result = [];
await transverse(user.group, result);
console.log(result);
Approach 1 fails to provide the correct array output and does not include Groups A to J. Approach 2 achieves the desired array, but the code lacks cleanliness. Can someone suggest an elegant solution to accomplish this task and explain why approach 1 falls short?