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
