Data aggregation is one of the most crucial operations when working with trees. Count the total number of files in a directory, find the overall size or a list of all files, and find all files according to a certain pattern - all of these are examples of data aggregation.
The key to aggregation operations is that the result is accumulated. The tree traversal by depth using the recursive process suits this task well. We looked at it in the previous lesson. We use it to traverse all the nodes of the tree and collect the result, starting from the lowest level.
Let's look at aggregation by the recursive process by counting the total number of nodes in a tree as an example. I.e., we want to know how many files and directories are in our file tree.
const tree = mkdir('/', [
mkdir('etc', [
mkfile('bashrc'),
mkfile('consul.cfg'),
]),
mkfile('hexletrc'),
mkdir('bin', [
mkfile('ls'),
mkfile('cat'),
]),
]);
// We use recursion,
// to get to the bottom of the tree
const getNodesCount = (tree) => {
if (isFile(tree)) {
// return 1 to count the current file
return 1;
}
// Get children if a node is a directory
const children = getChildren(tree);
// The hardest part
// Count the number of descendants for each child,
// by recursively calling our getNodesCount function
const descendantCounts = children.map(getNodesCount);
// Return 1 (current directory) + total number of descendants
return 1 + _.sum(descendantCounts);
};
getNodesCount(tree); // 8
https://repl.it/@hexlet/js-trees-aggregation-getNodesCount-nodejs
There's not much code here, but it's pretty clever. There are a few key points to note:
- The function checks the node type. If the node is a file, then the function returns 1
- If the node is a directory, then we get the children and call our function again for each child. Then we start all over again
- Calling a function on each child returns its own result (the number of its descendants). These results form an array with numbers that need to be combined
- At the end, it counts the total number of all descendants of the node + one (the current node itself)
You have to play around with this code before you can move on. It's the only way to get to grips with it.
Are there any more questions? Ask them in the Discussion section.
The Hexlet support team or other students will answer you.
For full access to the course you need a professional subscription.
A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.