I am fighting with this issue and not succeeding. I have the following tree:
It has two types of nodes, question and category. The categories are bolded and the questions have a circle next to them. The numbers in the category must show the subcategory coun for that node(easy), but the problem is the other number which must show the sum of the number of question type nodes in the levels below that node in the tree. And I am not able to do it.
My current version(after many):
if (treeNode.children && treeNode.children.length) {
treeNode.questionCount = 0;
treeNode.subcategoryCount = treeNode.children
.filter((item) => item.type === NODE_TYPES.CATEGORY).length;
for (let i = 0; i < treeNode.children.length; i++) {
treeNode.questionCount += enrichWithNumberOfSubcategoriesAndQuestions(treeNode.children[i]);
}
}
if (treeNode.type === NODE_TYPES.QUESTION) {
return 1;
} else if (treeNode.type === NODE_TYPES.CATEGORY) {
return treeNode.children
.filter((item) => item.type !== NODE_TYPES.CATEGORY).length;
}
return 0;
2
Answers
Here’s an approach. We are defining a recursive function which returns the number of questions inside the node.
The main idea is that you should first make the recursive calls so you are sure the child nodes have their count properties correctly set, and only then use that information to set the current node’s counter.
Here is an implementation. I added class definitions, a print function, and an initialisation of a tree based on your example. That way you can run this code here and verify it does the job: