evaluate.js 2.3 KB

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