Nested Sets for Javascript

On any modern site (and on older sites) there are nested structures, object hierarchies, trees. The most common example is a directory.



Today, many projects are being developed using Javascript. How to store tree structures in this case? This is what I would like to talk about.



Now my task is to draw up a hierarchical structure of the catalog based on product parameters.



There are various algorithms for storing trees, and examples of such algorithms are Adjacency List, Matherialized Path, Nested Set, and Closure Table.



If you can advise any more, I will be glad to hear and learn.



When writing extensions for Joomla, I used the Nested Set a lot. It was in this CMS that I first met this model. But now the stack has changed and now it's Javascript. The habits remain, and the Joomla sites too. It is necessary to transfer data to new services and projects.



There is quite a lot of information about Nested Sets on the Internet and you can always find it if you want, but nevertheless, I must say a few words about this data model.



The point of the Nested Set is that each node in the hierarchy has a left key and a right key pair. Depending on their values, the tree is traversed. The positive qualities of the algorithm, in my opinion, are the speed of data sampling. There is no recursion in this algorithm. At the same time, to change the tree structure, add, delete and transfer nodes, it is necessary to recalculate all the keys.



To use data from the Nested Set in Javascript projects, you need a module that can work with this model.



Searching through npm, I found modules whose functionality was to fetch data from the Nested Sets structure, i.e. all keys should have already been affixed. There was a need to edit the structure, but I did not find such an opportunity.



Another problem is that in most cases, both the data and the tree structure are stored in one entity, but in my opinion it is much more efficient to separate these things.



Thus, one and the same category (these categories) can lie in different parents. This will allow users to find what they are looking for faster with a well thought out hierarchy.



Although from an SEO point of view, there will be two pages with different URLs and the same content, but this can be solved by canonical links.



If this is not correct, I ask SEO specialists to correct me.



In the end, I decided to write a module and publish it on npmjs.com.



If it is useful to someone, I will be very glad.



Now I continue to work on it and in plans to implement the transfer of the node through the tree.



Here is a link to npm where you can download the package .



Here is a link to github where you can download the sources .



The documentation is there and there.



Any comments would be welcome.



We wish you good projects and interesting tasks.



All Articles