1 | import { deepMap } from '../../utils/collection';
|
2 | import { factory } from '../../utils/factory';
|
3 | var name = 'evaluate';
|
4 | var dependencies = ['typed', 'parse'];
|
5 | export var createEvaluate =
|
6 | /* #__PURE__ */
|
7 | factory(name, dependencies, function (_ref) {
|
8 | var typed = _ref.typed,
|
9 | parse = _ref.parse;
|
10 |
|
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 = {};
|
46 | return parse(expr).compile().evaluate(scope);
|
47 | },
|
48 | 'string, Object': function stringObject(expr, scope) {
|
49 | return parse(expr).compile().evaluate(scope);
|
50 | },
|
51 | 'Array | Matrix': function ArrayMatrix(expr) {
|
52 | var scope = {};
|
53 | return deepMap(expr, function (entry) {
|
54 | return parse(entry).compile().evaluate(scope);
|
55 | });
|
56 | },
|
57 | 'Array | Matrix, Object': function ArrayMatrixObject(expr, scope) {
|
58 | return deepMap(expr, function (entry) {
|
59 | return parse(entry).compile().evaluate(scope);
|
60 | });
|
61 | }
|
62 | });
|
63 | }); |
\ | No newline at end of file |