In this article, I will show you a simple JavaScript algorithm to build a tree, using functional programming.
_Also available _in french
In my journey of developing Naept, I encountered the need to build trees. An easy example of what is a tree, are the chapters of a document. If the document is the trunk, all the main chapters are the branches of that tree. And all those main chapters may be divided into sub-chapters, which may be, in turn, again sub-divided in sub-sub-chapters, and so on…
The most simple thing to do when storing objects that constitute a tree inside a database is giving them a link to their parent.
So each one of my chapters has a parent_id
property. And if this parent_id
’s value is null
for some elements, that means that they are each the root element of a tree.
So from this point, in theory, we should be able to “build a tree”, and what I mean by that is creating a software representation of this tree:
Yes, I know my tree is weird, growing from the left to the right instead of growing up. But you get the idea!
#javascript #algorithms #functional-programming #recursion #trees