compile.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import { deepMap } from '../../utils/collection.js';
  2. import { factory } from '../../utils/factory.js';
  3. var name = 'compile';
  4. var dependencies = ['typed', 'parse'];
  5. export var createCompile = /* #__PURE__ */factory(name, dependencies, _ref => {
  6. var {
  7. typed,
  8. parse
  9. } = _ref;
  10. /**
  11. * Parse and compile an expression.
  12. * Returns a an object with a function `evaluate([scope])` to evaluate the
  13. * compiled expression.
  14. *
  15. * Syntax:
  16. *
  17. * math.compile(expr) // returns one node
  18. * math.compile([expr1, expr2, expr3, ...]) // returns an array with nodes
  19. *
  20. * Examples:
  21. *
  22. * const code1 = math.compile('sqrt(3^2 + 4^2)')
  23. * code1.evaluate() // 5
  24. *
  25. * let scope = {a: 3, b: 4}
  26. * const code2 = math.compile('a * b') // 12
  27. * code2.evaluate(scope) // 12
  28. * scope.a = 5
  29. * code2.evaluate(scope) // 20
  30. *
  31. * const nodes = math.compile(['a = 3', 'b = 4', 'a * b'])
  32. * nodes[2].evaluate() // 12
  33. *
  34. * See also:
  35. *
  36. * parse, evaluate
  37. *
  38. * @param {string | string[] | Array | Matrix} expr
  39. * The expression to be compiled
  40. * @return {{evaluate: Function} | Array.<{evaluate: Function}>} code
  41. * An object with the compiled expression
  42. * @throws {Error}
  43. */
  44. return typed(name, {
  45. string: function string(expr) {
  46. return parse(expr).compile();
  47. },
  48. 'Array | Matrix': function ArrayMatrix(expr) {
  49. return deepMap(expr, function (entry) {
  50. return parse(entry).compile();
  51. });
  52. }
  53. });
  54. });