UNPKG

8.35 kBJavaScriptView Raw
1import { isNode } from '../../utils/is';
2import { keywords } from '../keywords';
3import { escape } from '../../utils/string';
4import { forEach, join } from '../../utils/array';
5import { toSymbol } from '../../utils/latex';
6import { getPrecedence } from '../operators';
7import { setSafeProperty } from '../../utils/customs';
8import { factory } from '../../utils/factory';
9var name = 'FunctionAssignmentNode';
10var dependencies = ['typed', 'Node'];
11export var createFunctionAssignmentNode = /* #__PURE__ */factory(name, dependencies, function (_ref) {
12 var typed = _ref.typed,
13 Node = _ref.Node;
14
15 /**
16 * @constructor FunctionAssignmentNode
17 * @extends {Node}
18 * Function assignment
19 *
20 * @param {string} name Function name
21 * @param {string[] | Array.<{name: string, type: string}>} params
22 * Array with function parameter names, or an
23 * array with objects containing the name
24 * and type of the parameter
25 * @param {Node} expr The function expression
26 */
27 function FunctionAssignmentNode(name, params, expr) {
28 if (!(this instanceof FunctionAssignmentNode)) {
29 throw new SyntaxError('Constructor must be called with the new operator');
30 } // validate input
31
32
33 if (typeof name !== 'string') throw new TypeError('String expected for parameter "name"');
34 if (!Array.isArray(params)) throw new TypeError('Array containing strings or objects expected for parameter "params"');
35 if (!isNode(expr)) throw new TypeError('Node expected for parameter "expr"');
36 if (name in keywords) throw new Error('Illegal function name, "' + name + '" is a reserved keyword');
37 this.name = name;
38 this.params = params.map(function (param) {
39 return param && param.name || param;
40 });
41 this.types = params.map(function (param) {
42 return param && param.type || 'any';
43 });
44 this.expr = expr;
45 }
46
47 FunctionAssignmentNode.prototype = new Node();
48 FunctionAssignmentNode.prototype.type = 'FunctionAssignmentNode';
49 FunctionAssignmentNode.prototype.isFunctionAssignmentNode = true;
50 /**
51 * Compile a node into a JavaScript function.
52 * This basically pre-calculates as much as possible and only leaves open
53 * calculations which depend on a dynamic scope with variables.
54 * @param {Object} math Math.js namespace with functions and constants.
55 * @param {Object} argNames An object with argument names as key and `true`
56 * as value. Used in the SymbolNode to optimize
57 * for arguments from user assigned functions
58 * (see FunctionAssignmentNode) or special symbols
59 * like `end` (see IndexNode).
60 * @return {function} Returns a function which can be called like:
61 * evalNode(scope: Object, args: Object, context: *)
62 */
63
64 FunctionAssignmentNode.prototype._compile = function (math, argNames) {
65 var childArgNames = Object.create(argNames);
66 forEach(this.params, function (param) {
67 childArgNames[param] = true;
68 }); // compile the function expression with the child args
69
70 var evalExpr = this.expr._compile(math, childArgNames);
71
72 var name = this.name;
73 var params = this.params;
74 var signature = join(this.types, ',');
75 var syntax = name + '(' + join(this.params, ', ') + ')';
76 return function evalFunctionAssignmentNode(scope, args, context) {
77 var signatures = {};
78
79 signatures[signature] = function () {
80 var childArgs = Object.create(args);
81
82 for (var i = 0; i < params.length; i++) {
83 childArgs[params[i]] = arguments[i];
84 }
85
86 return evalExpr(scope, childArgs, context);
87 };
88
89 var fn = typed(name, signatures);
90 fn.syntax = syntax;
91 setSafeProperty(scope, name, fn);
92 return fn;
93 };
94 };
95 /**
96 * Execute a callback for each of the child nodes of this node
97 * @param {function(child: Node, path: string, parent: Node)} callback
98 */
99
100
101 FunctionAssignmentNode.prototype.forEach = function (callback) {
102 callback(this.expr, 'expr', this);
103 };
104 /**
105 * Create a new FunctionAssignmentNode having it's childs be the results of calling
106 * the provided callback function for each of the childs of the original node.
107 * @param {function(child: Node, path: string, parent: Node): Node} callback
108 * @returns {FunctionAssignmentNode} Returns a transformed copy of the node
109 */
110
111
112 FunctionAssignmentNode.prototype.map = function (callback) {
113 var expr = this._ifNode(callback(this.expr, 'expr', this));
114
115 return new FunctionAssignmentNode(this.name, this.params.slice(0), expr);
116 };
117 /**
118 * Create a clone of this node, a shallow copy
119 * @return {FunctionAssignmentNode}
120 */
121
122
123 FunctionAssignmentNode.prototype.clone = function () {
124 return new FunctionAssignmentNode(this.name, this.params.slice(0), this.expr);
125 };
126 /**
127 * Is parenthesis needed?
128 * @param {Node} node
129 * @param {Object} parenthesis
130 * @private
131 */
132
133
134 function needParenthesis(node, parenthesis) {
135 var precedence = getPrecedence(node, parenthesis);
136 var exprPrecedence = getPrecedence(node.expr, parenthesis);
137 return parenthesis === 'all' || exprPrecedence !== null && exprPrecedence <= precedence;
138 }
139 /**
140 * get string representation
141 * @param {Object} options
142 * @return {string} str
143 */
144
145
146 FunctionAssignmentNode.prototype._toString = function (options) {
147 var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep';
148 var expr = this.expr.toString(options);
149
150 if (needParenthesis(this, parenthesis)) {
151 expr = '(' + expr + ')';
152 }
153
154 return this.name + '(' + this.params.join(', ') + ') = ' + expr;
155 };
156 /**
157 * Get a JSON representation of the node
158 * @returns {Object}
159 */
160
161
162 FunctionAssignmentNode.prototype.toJSON = function () {
163 var types = this.types;
164 return {
165 mathjs: 'FunctionAssignmentNode',
166 name: this.name,
167 params: this.params.map(function (param, index) {
168 return {
169 name: param,
170 type: types[index]
171 };
172 }),
173 expr: this.expr
174 };
175 };
176 /**
177 * Instantiate an FunctionAssignmentNode from its JSON representation
178 * @param {Object} json An object structured like
179 * `{"mathjs": "FunctionAssignmentNode", name: ..., params: ..., expr: ...}`,
180 * where mathjs is optional
181 * @returns {FunctionAssignmentNode}
182 */
183
184
185 FunctionAssignmentNode.fromJSON = function (json) {
186 return new FunctionAssignmentNode(json.name, json.params, json.expr);
187 };
188 /**
189 * get HTML representation
190 * @param {Object} options
191 * @return {string} str
192 */
193
194
195 FunctionAssignmentNode.prototype.toHTML = function (options) {
196 var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep';
197 var params = [];
198
199 for (var i = 0; i < this.params.length; i++) {
200 params.push('<span class="math-symbol math-parameter">' + escape(this.params[i]) + '</span>');
201 }
202
203 var expr = this.expr.toHTML(options);
204
205 if (needParenthesis(this, parenthesis)) {
206 expr = '<span class="math-parenthesis math-round-parenthesis">(</span>' + expr + '<span class="math-parenthesis math-round-parenthesis">)</span>';
207 }
208
209 return '<span class="math-function">' + escape(this.name) + '</span>' + '<span class="math-parenthesis math-round-parenthesis">(</span>' + params.join('<span class="math-separator">,</span>') + '<span class="math-parenthesis math-round-parenthesis">)</span><span class="math-operator math-assignment-operator math-variable-assignment-operator math-binary-operator">=</span>' + expr;
210 };
211 /**
212 * get LaTeX representation
213 * @param {Object} options
214 * @return {string} str
215 */
216
217
218 FunctionAssignmentNode.prototype._toTex = function (options) {
219 var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep';
220 var expr = this.expr.toTex(options);
221
222 if (needParenthesis(this, parenthesis)) {
223 expr = "\\left(".concat(expr, "\\right)");
224 }
225
226 return '\\mathrm{' + this.name + '}\\left(' + this.params.map(toSymbol).join(',') + '\\right):=' + expr;
227 };
228
229 return FunctionAssignmentNode;
230}, {
231 isClass: true,
232 isNode: true
233});
\No newline at end of file