UNPKG

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