Javascript: Map, filter, reduce

JS: Trees
Last update: 08 Nov 23:20
0
Students

In the JS: Functions course we went through three main higher-order functions for handling collections: map, filter and reduce. You can use them to solve almost any task.

solution.js

In this challenge, you will have to write your own implementation of these functions for file trees.

map takes a handler function and a tree, and returns a mapped tree.

filter takes a predicate and a tree, and returns a filtered tree by predicate.

In addition to the main parameters (the handler function and the tree), reduce also takes the initial value of the accumulator.

All functions must be exported.

Examples

import { mkdir, mkfile, getName, isDirectory } from '@hexlet/immutable-fs-trees';

const tree = mkdir('/', [
  mkdir('eTc', [
    mkfile('config.json')
  ]),
]);

Making the names of all directories and files uppercase:

map(n => ({ ...n, name: getName(n).toUpperCase() }), tree);
// {
//   name: '/',
//   type: 'directory',
//   meta: {},
//   children: [
//     {
//       name: 'ETC',
//       type: 'directory',
//       meta: {},
//       children: [{ name: 'CONFIG.JSON', type: 'file', meta: {} }],
//     },
//   ],
// }

Filtering directories:

filter((n) => isDirectory(n), tree);
// {
//   name: '/',
//   type: 'directory',
//   meta: {},
//   children: [
//     {
//       name: 'etc',
//       type: 'directory',
//       meta: {},
//       children: [],
//     },
//   ],
// }

Counting tree nodes:

reduce((acc, n) => acc + 1, tree, 0); // 3

For full access to the challenge 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.

Get access
130
courses
1000
exercises
2000+
hours of theory
3200
tests