UNPKG

1.49 kBJavaScriptView Raw
1const { parse, ConstantNode } = require('../..')
2
3// Filter an expression tree
4console.log('Filter all symbol nodes "x" in the expression "x^2 + x/4 + 3*y"')
5const node = parse('x^2 + x/4 + 3*y')
6const filtered = node.filter(function (node) {
7 return node.isSymbolNode && node.name === 'x'
8})
9// returns an array with two entries: two SymbolNodes 'x'
10
11filtered.forEach(function (node) {
12 console.log(node.type, node.toString())
13})
14// outputs:
15// SymbolNode x
16// SymbolNode x
17
18// Traverse an expression tree
19console.log()
20console.log('Traverse the expression tree of expression "3 * x + 2"')
21const node1 = parse('3 * x + 2')
22node1.traverse(function (node, path, parent) {
23 switch (node.type) {
24 case 'OperatorNode':
25 console.log(node.type, node.op)
26 break
27 case 'ConstantNode':
28 console.log(node.type, node.value)
29 break
30 case 'SymbolNode':
31 console.log(node.type, node.name)
32 break
33 default: console.log(node.type)
34 }
35})
36// outputs:
37// OperatorNode +
38// OperatorNode *
39// ConstantNode 3
40// SymbolNode x
41// ConstantNode 2
42
43// transform an expression tree
44console.log()
45console.log('Replace all symbol nodes "x" in expression "x^2 + 5*x" with a constant 3')
46const node2 = parse('x^2 + 5*x')
47const transformed = node2.transform(function (node, path, parent) {
48 if (node.isSymbolNode && node.name === 'x') {
49 return new ConstantNode(3)
50 } else {
51 return node
52 }
53})
54console.log(transformed.toString())
55// outputs: '3 ^ 2 + 5 * 3'