UNPKG

1.78 kBJavaScriptView Raw
1import { isFunctionNode, isNode, isOperatorNode, isParenthesisNode, isSymbolNode } from '../../../utils/is'
2import { factory } from '../../../utils/factory'
3
4const name = 'resolve'
5const dependencies = [
6 'parse',
7 'FunctionNode',
8 'OperatorNode',
9 'ParenthesisNode'
10]
11
12export const createResolve = /* #__PURE__ */ factory(name, dependencies, ({
13 parse,
14 FunctionNode,
15 OperatorNode,
16 ParenthesisNode
17}) => {
18 /**
19 * resolve(expr, scope) replaces variable nodes with their scoped values
20 *
21 * Syntax:
22 *
23 * simplify.resolve(expr, scope)
24 *
25 * Examples:
26 *
27 * math.simplify.resolve('x + y', {x:1, y:2}) // Node {1 + 2}
28 * math.simplify.resolve(math.parse('x+y'), {x:1, y:2}) // Node {1 + 2}
29 * math.simplify('x+y', {x:2, y:'x+x'}).toString() // "6"
30 *
31 * @param {Node} node
32 * The expression tree to be simplified
33 * @param {Object} scope with variables to be resolved
34 */
35 function resolve (node, scope) {
36 if (!scope) {
37 return node
38 }
39 if (isSymbolNode(node)) {
40 const value = scope[node.name]
41 if (isNode(value)) {
42 return resolve(value, scope)
43 } else if (typeof value === 'number') {
44 return parse(String(value))
45 }
46 } else if (isOperatorNode(node)) {
47 const args = node.args.map(function (arg) {
48 return resolve(arg, scope)
49 })
50 return new OperatorNode(node.op, node.fn, args, node.implicit)
51 } else if (isParenthesisNode(node)) {
52 return new ParenthesisNode(resolve(node.content, scope))
53 } else if (isFunctionNode(node)) {
54 const args = node.args.map(function (arg) {
55 return resolve(arg, scope)
56 })
57 return new FunctionNode(node.name, args)
58 }
59 return node
60 }
61
62 return resolve
63})