tree-transformer

1.0.0 • Public • Published

Tree Transformer

Transform nodes in the tree.

Like Tree Visitor, but methods can return a value to replace the node being processed.

API

var Transformer = require('tree-transformer');
var nodes = [
    { type: 'number', value: 1 },
    { type: 'string', value: 'abc', quote: '"' }
];
 
function MyTransformer() {}
MyTransformer.prototype = new Transformer();
 
MyTransformer.prototype.visit_node = function (node) {
     return node.value;
};
 
new MyTransformer().visit(nodes); // nodes now equals to [1, 'abc']

Replacing only happens when visit an array of nodes.

Some returned values have special meanings:

  • null - remove the node

  • undefined - do nothing to the node

  • an array of nodes - replace the node with the array of nodes. The result array is flattened.

    var Transformer = require('tree-transformer');
    var nodes = [
        { type: 'number', value: 1 }
        { type: 'number', value: 3 }
    ];
     
    function MyTransformer() {}
    MyTransformer.prototype = new Transformer();
     
    MyTransformer.prototype.visit_number = function (number) {
       return [number.value, number.value + 1];
    };
     
    new MyTransformer().visit(nodes); // nodes now equals to [1, 2, 3, 4]
  • others - replace the node with the value

When visiting a single node, visit(node) returns the returning value of the corresponding method, unless it's undefined, in which case the original node will be returned.

When visiting an array of nodes, the result array will be returned.

Readme

Keywords

none

Package Sidebar

Install

npm i tree-transformer

Weekly Downloads

8

Version

1.0.0

License

MIT

Last publish

Collaborators

  • curvedmark