simple-squiggle

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

compileInlineExpression.js (1024B)


      1 import { isSymbolNode } from '../../../utils/is.js';
      2 import { createSubScope } from '../../../utils/scope.js';
      3 /**
      4  * Compile an inline expression like "x > 0"
      5  * @param {Node} expression
      6  * @param {Object} math
      7  * @param {Object} scope
      8  * @return {function} Returns a function with one argument which fills in the
      9  *                    undefined variable (like "x") and evaluates the expression
     10  */
     11 
     12 export function compileInlineExpression(expression, math, scope) {
     13   // find an undefined symbol
     14   var symbol = expression.filter(function (node) {
     15     return isSymbolNode(node) && !(node.name in math) && !scope.has(node.name);
     16   })[0];
     17 
     18   if (!symbol) {
     19     throw new Error('No undefined variable found in inline expression "' + expression + '"');
     20   } // create a test function for this equation
     21 
     22 
     23   var name = symbol.name; // variable name
     24 
     25   var subScope = createSubScope(scope);
     26   var eq = expression.compile();
     27   return function inlineExpression(x) {
     28     subScope.set(name, x);
     29     return eq.evaluate(subScope);
     30   };
     31 }