liveBook · Manning

Tree.map

As explained in Functional Programming in JavaScript

A tree traversal operation that applies a function to each node value while preserving the tree structure.

Tree.map applies a function to every node value during a recursive preorder traversal while retaining the tree’s parent-child structure. Its behavior parallels Array.prototype.map, extending structure-preserving mapping to trees. section 3.5

The traversal proceeds in a consistent order:

  • Process the root node’s value. section 3.5
  • Recursively process each child and its descendants. section 3.5
  • Return a tree with transformed values and the same connections. section 3.5

Mapping person objects to names

Given a tree rooted at church, Tree.map(church, p => p.fullname) transforms each Person value into its full name, producing names in preorder: Alonzo Church, Barkley Rosser, Elliot Mendelson, Gerald Sacks, Alan Turing, Robin Gandy, Stephen Kleene, Nels Nelson, and Robert Constable. section 3.5

class Tree {
   constructor(root) {
      this._root = root;
   }
   static map(node, fn, tree = null) {                     #1
      node.value = fn(node.value);                         #2
      if(tree === null) {
          tree = new Tree(node);                           #3
      }
      if(node.hasChildren()) {                             #4
        _.map(node.children, function (child) {            #5
            Tree.map(child, fn, tree);                     #6
        });
      }
      return tree;
   }
       get root() {
          return this._root;
       }
   }

The implementation updates the current node, creates the result tree at the root, and recursively maps over children. section 3.5

How Functional Programming in JavaScript covers it

How deep it goes
Explains preorder recursion and shows the implementation, while deferring formal treatment of mapping over types.
Examples
Uses a tree of mathematicians and maps Person objects to fullname strings in preorder.
What it assumes
Assumes basic JavaScript functions and objects while developing recursion, trees, and higher-order mapping from concrete examples.
What you can do after
Apply it via Tree.map to transform every node value without redesigning the tree’s structure.
How it connects
Connects tree traversal with recursion, higher-order functions, Array.prototype.map, immutability, and side-effect-free data types.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Programming in JavaScript. The section links point to the parts of the book it draws on.