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:
You have to play around with this code before you can move on. It's the only way to get to grips with it.
The Hexlet support team or other students will answer you.
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.
Programming courses for beginners and experienced developers. Start training for free
Our graduates work in companies:
Sign up or sign in
Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.