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…

Inside the database

The most simple thing to do when storing objects that constitute a tree inside a database is giving them a link to their parent.

Image for post

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.

Image for post

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:

Image for post

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

A simple tree building algorithm — Naept
1.35 GEEK