UNPKG

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