Tree Visitor
Visit nodes in the tree.
Example
Visit a single node:
var Visitor = ;var node = type: 'number' value: 1 ; {}MyVisitorprototype = ; MyVisitorprototype { console;}; var myVisitor = ;myVisitor; // 1
Visit an array of nodes:
var Visitor = ;var nodes = type: 'number' value: 1 type: 'string' value: 'abc' quote: '"' ; {}MyVisitorprototype = ; MyVisitorprototype { console;}; MyVisitorprototype { console;}; var myVisitor = ;myVisitor; // 1 "abc"
Visit nested nodes:
var Visitor = ;var number = type: 'number' value: 1 ;var string = type: 'string' value: 'abc' ;var expression = type: 'binaryExpression' operator: '+' left: number right: string; {}MyVisitorprototype = ; MyVisitorprototype { this; console; this;}; MyVisitorprototype { console;}; MyVisitorprototype { console;}; var myVisitor = ;myVisitor; // 1 + "abc"
One method to rule them all:
var Visitor = ; var nodes = type: 'number' value: 1 type: 'string' value: 'abc' quote: '"' ; {}MyVisitorprototype = ; MyVisitorprototype { console;}; var myVisitor = ;myVisitor; // 1 abc
API
var Visitor = ; {}MyVisitorprototype = ; MyVisitorprototype {}; var myVisitor = ;myVisitor;
Visitor
should be "subclassed" by a constructor, the new constructor should have methods like .visit_nodeType()
, and the node being visited should have a type
property. If the value of type
and the string after .visit_
matches, the node will be passed to that method when calling .visit(node)
.
Either a single node (any js object), or an array of nodes can be visited. In the latter case, the nodes are visited sequentially.
.visit_node()
is a special method, if the node being visited doesn't have a corresponding method, it's passed to .visit_node()
. If it does, however, it will not be passed to this method.
Nodes that are not a plain object (e.g., string, null
, etc) or don't have a type
property are ignored (i.e., it's not passed to any method, not even .visit_node()
).
When visiting a single node, the returning value of .visit(node)
is the returning value of the corresponding method, or the node itself if it doesn't have a corresponding method.
When visiting an array of nodes, the returning value of .visit(nodes)
is the original array (i.e., nodes
).