Graph traversal

Traverses and optionally transforms a graph.
$root.traverse(
    descend: node -> parent -> lastResult -> { ... }, 
    mapping: node -> parent -> lastResult -> { ... }, 
    compose: result -> childResults -> node -> parent -> { ... }
)

The traversal takes place in the following order:

  1. The root node is visited by applying the function mapping to it. The result of the visit is used in step 4.
  2. The next nodes to be visited are calculated by applying the function descend to the current node.
  3. All subsequent nodes are processed recursively in the same way.
  4. When the recursion returns, the optional function compose is applied to the results generated for the current node and all its child nodes. The result of compose returns the final result of traverse. If no function compose is specified, the result of traverse is the result generated by the mapping function for the root node.

Parameter root

Type: Any object.

The traversal of the graph starts with this object.

Parameter descend (mandatory)

Type: Function with up to three arguments (node, parent, lastResult ).

The descent in the graph is specified by the function descend, which calculates the next nodes to be visited after the current node. The function descend accepts the current node and optionally the parent node as well as the last result of the visit (lastResult). The last result is the return of the mapping function if a node is found more than once (otherwise null). The argument lastResult can be used to stop the visit to prevent endless recursion when traversing a cyclic graph (or to shorten the visit when traversing a directed acyclic graph).

Parameter mapping (mandatory)

Type: Function with up to three arguments (node, parent, lastResult).

The mapping generates the result of the visit to a node. If traverse is used in a transaction, an operation can be performed on a node here; if mapping is not specified, the result of the visit is the visited node itself.

Parameter compose (optional)

Type: Function with up to four arguments (result, childResults, node, parent).

The function generates the final result of traverse after the mapping result of a node and its children is available. If compose is not specified, the result of the transformation operation is the result of the mapping function applied to the root node.

The parameters of compose are

  • result: The result generated by the mapping function for the current node.
  • childResultsA list of the results generated for each visited child of the current node.
  • nodeThe current node.
  • parentThe parent node of the current node.