evaluate.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { deepMap } from '../../utils/collection.js';
  2. import { factory } from '../../utils/factory.js';
  3. import { createEmptyMap } from '../../utils/map.js';
  4. var name = 'evaluate';
  5. var dependencies = ['typed', 'parse'];
  6. export var createEvaluate = /* #__PURE__ */factory(name, dependencies, _ref => {
  7. var {
  8. typed,
  9. parse
  10. } = _ref;
  11. /**
  12. * Evaluate an expression.
  13. *
  14. * Note the evaluating arbitrary expressions may involve security risks,
  15. * see [https://mathjs.org/docs/expressions/security.html](https://mathjs.org/docs/expressions/security.html) for more information.
  16. *
  17. * Syntax:
  18. *
  19. * math.evaluate(expr)
  20. * math.evaluate(expr, scope)
  21. * math.evaluate([expr1, expr2, expr3, ...])
  22. * math.evaluate([expr1, expr2, expr3, ...], scope)
  23. *
  24. * Example:
  25. *
  26. * math.evaluate('(2+3)/4') // 1.25
  27. * math.evaluate('sqrt(3^2 + 4^2)') // 5
  28. * math.evaluate('sqrt(-4)') // 2i
  29. * math.evaluate(['a=3', 'b=4', 'a*b']) // [3, 4, 12]
  30. *
  31. * let scope = {a:3, b:4}
  32. * math.evaluate('a * b', scope) // 12
  33. *
  34. * See also:
  35. *
  36. * parse, compile
  37. *
  38. * @param {string | string[] | Matrix} expr The expression to be evaluated
  39. * @param {Object} [scope] Scope to read/write variables
  40. * @return {*} The result of the expression
  41. * @throws {Error}
  42. */
  43. return typed(name, {
  44. string: function string(expr) {
  45. var scope = createEmptyMap();
  46. return parse(expr).compile().evaluate(scope);
  47. },
  48. 'string, Map | Object': function stringMapObject(expr, scope) {
  49. return parse(expr).compile().evaluate(scope);
  50. },
  51. 'Array | Matrix': function ArrayMatrix(expr) {
  52. var scope = createEmptyMap();
  53. return deepMap(expr, function (entry) {
  54. return parse(entry).compile().evaluate(scope);
  55. });
  56. },
  57. 'Array | Matrix, Map | Object': function ArrayMatrixMapObject(expr, scope) {
  58. return deepMap(expr, function (entry) {
  59. return parse(entry).compile().evaluate(scope);
  60. });
  61. }
  62. });
  63. });