compileInlineExpression.js 1023 B

1234567891011121314151617181920212223242526272829
  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. export function compileInlineExpression(expression, math, scope) {
  12. // find an undefined symbol
  13. var symbol = expression.filter(function (node) {
  14. return isSymbolNode(node) && !(node.name in math) && !scope.has(node.name);
  15. })[0];
  16. if (!symbol) {
  17. throw new Error('No undefined variable found in inline expression "' + expression + '"');
  18. }
  19. // create a test function for this equation
  20. var name = symbol.name; // variable name
  21. var subScope = createSubScope(scope);
  22. var eq = expression.compile();
  23. return function inlineExpression(x) {
  24. subScope.set(name, x);
  25. return eq.evaluate(subScope);
  26. };
  27. }