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