1 | const { parse, ConstantNode } = require('../..')
|
2 |
|
3 |
|
4 | console.log('Filter all symbol nodes "x" in the expression "x^2 + x/4 + 3*y"')
|
5 | const node = parse('x^2 + x/4 + 3*y')
|
6 | const filtered = node.filter(function (node) {
|
7 | return node.isSymbolNode && node.name === 'x'
|
8 | })
|
9 |
|
10 |
|
11 | filtered.forEach(function (node) {
|
12 | console.log(node.type, node.toString())
|
13 | })
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 | console.log()
|
20 | console.log('Traverse the expression tree of expression "3 * x + 2"')
|
21 | const node1 = parse('3 * x + 2')
|
22 | node1.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 |
|
37 |
|
38 |
|
39 |
|
40 |
|
41 |
|
42 |
|
43 |
|
44 | console.log()
|
45 | console.log('Replace all symbol nodes "x" in expression "x^2 + 5*x" with a constant 3')
|
46 | const node2 = parse('x^2 + 5*x')
|
47 | const 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 | })
|
54 | console.log(transformed.toString())
|
55 |
|