Let's practice one more data aggregation technique on file systems. Let's write a function that takes a directory as input and returns a list of directories on the first level of nesting and the number of files inside each of them, including all subdirectories.
const tree = mkdir('/', [
mkdir('etc', [
mkdir('apache'),
mkdir('nginx', [
mkfile('nginx.conf'),
]),
]),
mkdir('consul', [
mkfile('config.json'),
mkfile('file.tmp'),
mkdir('data'),
]),
mkfile('hosts'),
mkfile('resolve'),
]);
console.log(getSubdirectoriesInfo(tree));
// => [['etc', 1], ['consul', 2]]
This task breaks down into two smaller ones:
Let's start by counting the number of files. This is a classic aggregation task:
const getFilesCount = (node) => {
if (isFile(node)) {
return 1;
}
const children = getChildren(node);
const descendantCounts = children.map(getFilesCount);
return _.sum(descendantCounts);
};
The next step is to extract all the children from the initial node and apply a count to each of them:
const getSubdirectoriesInfo = (tree) => {
const children = getChildren(tree);
const result = children
// We're only interested in directories
.filter(isDirectory)
// Counting in each directory
.map((child) => [getName(child), getFilesCount(child)]);
return result;
};
I.e., we accessed the children directly by first filtering them, and mapped them to the desired array, which contained the name and number of files for each directory.
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.