UNPKG

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