I came across an interesting problem I needed to tackle within MST regarding Tree Traversing.

My interesting problem

I am using MST to create a document template, and using that same template to create a document from it. However, I later needed to develop the functionality to allow the document owner to upgrade the template of the document they have created.

What I needed to do was essentially visit every node within the template and compare that to the documents node (or treat them as new nodes). Then I do the same comparison the other way around to detect if any nodes have been removed.

What the end goal is, to present the user with information about what has changed and give them the option to reconcile between the new template and document.

Code!

For the sake of this article, I’m going to make my models simple.

This should be familiar to you. We have our Section model and our Content model.

Now let’s create our nodes extractor.

This pure JavaScript function will allow us to traverse through the tree. We start by checking if the node is a Section, if so, we dive deeper into the tree. We are using yield and yield* in order to allow use to enumerate through the tree.

A similar way we could have done this would be to reduce the whole tree but I am using yield in case I ever needed to stop calculating which means I will save myself the effort of going through the rest of the tree (in a global search for example). (read more about yield at the bottom of this article)

A full solution to my problem would be something like this:

Note: if you are using Babel and ES6, you will need to add “@babel/plugin-transform-regenerator” plugin and also add "@babel/polyfill" to your webpack config entry.

npm i -D @babel/plugin-transform-regenerator