simple-squiggle

A restricted subset of Squiggle
Log | Files | Refs | README

expression_trees.js (1492B)


      1 const { parse, ConstantNode } = require('../..')
      2 
      3 // Filter an expression tree
      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 // returns an array with two entries: two SymbolNodes 'x'
     10 
     11 filtered.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
     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 // outputs:
     37 //   OperatorNode +
     38 //   OperatorNode *
     39 //   ConstantNode 3
     40 //   SymbolNode x
     41 //   ConstantNode 2
     42 
     43 // transform an expression tree
     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 // outputs: '3 ^ 2 + 5 * 3'