JS: Trees
Theory: Manipulating the virtual file system
The library we use to build trees is designed only for immutable file structures. I.e., once it's created, it cannot be modified. But it is possible to make a new structure based on the old one with some parts being changed.
The immutable structure is not some random choice. Such a structure is easier to debug and there are fewer chances to make mistakes. Also it allows you to fully dig into using higher-order functions.
Basic operations with nodes
The @hexlet/immutable-fs-trees package allows you to not only create files but also to extract data from previously created files and directories using basic operations. They allow you to hide the internal structure of the tree itself:
Additionally, there are two functions in the package to check the type. They can be used to selectively work with files and directories:
The above operations are enough to perform any operations on files and directories. Let's start with the simplest ones, which do not require recursive traversal.
Processing
Any immutable-style processing boils down to generating new data from old. Below, we'll implement some processing examples that reveal this idea.
Changing the file name
This actually creates a new file with the metadata of the old one. Before creating a new file, the metadata is cloned (using deep cloning). Why? Objects are referential data, so if you do not clone them, the new file metadata will contain the old metadata. As soon as we want to change something, we change the new one and thus break the old one:

