FunctionAssignmentNode.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. "use strict";
  2. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
  3. Object.defineProperty(exports, "__esModule", {
  4. value: true
  5. });
  6. exports.createFunctionAssignmentNode = void 0;
  7. var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
  8. var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
  9. var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
  10. var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));
  11. var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));
  12. var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
  13. var _is = require("../../utils/is.js");
  14. var _keywords = require("../keywords.js");
  15. var _string = require("../../utils/string.js");
  16. var _array = require("../../utils/array.js");
  17. var _latex = require("../../utils/latex.js");
  18. var _operators = require("../operators.js");
  19. var _factory = require("../../utils/factory.js");
  20. function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
  21. function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
  22. function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
  23. function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; }
  24. function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
  25. var name = 'FunctionAssignmentNode';
  26. var dependencies = ['typed', 'Node'];
  27. var createFunctionAssignmentNode = /* #__PURE__ */(0, _factory.factory)(name, dependencies, function (_ref) {
  28. var typed = _ref.typed,
  29. Node = _ref.Node;
  30. /**
  31. * Is parenthesis needed?
  32. * @param {Node} node
  33. * @param {Object} parenthesis
  34. * @param {string} implicit
  35. * @private
  36. */
  37. function needParenthesis(node, parenthesis, implicit) {
  38. var precedence = (0, _operators.getPrecedence)(node, parenthesis, implicit);
  39. var exprPrecedence = (0, _operators.getPrecedence)(node.expr, parenthesis, implicit);
  40. return parenthesis === 'all' || exprPrecedence !== null && exprPrecedence <= precedence;
  41. }
  42. var FunctionAssignmentNode = /*#__PURE__*/function (_Node) {
  43. (0, _inherits2["default"])(FunctionAssignmentNode, _Node);
  44. var _super = _createSuper(FunctionAssignmentNode);
  45. /**
  46. * @constructor FunctionAssignmentNode
  47. * @extends {Node}
  48. * Function assignment
  49. *
  50. * @param {string} name Function name
  51. * @param {string[] | Array.<{name: string, type: string}>} params
  52. * Array with function parameter names, or an
  53. * array with objects containing the name
  54. * and type of the parameter
  55. * @param {Node} expr The function expression
  56. */
  57. function FunctionAssignmentNode(name, params, expr) {
  58. var _this;
  59. (0, _classCallCheck2["default"])(this, FunctionAssignmentNode);
  60. _this = _super.call(this);
  61. // validate input
  62. if (typeof name !== 'string') {
  63. throw new TypeError('String expected for parameter "name"');
  64. }
  65. if (!Array.isArray(params)) {
  66. throw new TypeError('Array containing strings or objects expected for parameter "params"');
  67. }
  68. if (!(0, _is.isNode)(expr)) {
  69. throw new TypeError('Node expected for parameter "expr"');
  70. }
  71. if (_keywords.keywords.has(name)) {
  72. throw new Error('Illegal function name, "' + name + '" is a reserved keyword');
  73. }
  74. var paramNames = new Set();
  75. var _iterator = _createForOfIteratorHelper(params),
  76. _step;
  77. try {
  78. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  79. var param = _step.value;
  80. var _name = typeof param === 'string' ? param : param.name;
  81. if (paramNames.has(_name)) {
  82. throw new Error("Duplicate parameter name \"".concat(_name, "\""));
  83. } else {
  84. paramNames.add(_name);
  85. }
  86. }
  87. } catch (err) {
  88. _iterator.e(err);
  89. } finally {
  90. _iterator.f();
  91. }
  92. _this.name = name;
  93. _this.params = params.map(function (param) {
  94. return param && param.name || param;
  95. });
  96. _this.types = params.map(function (param) {
  97. return param && param.type || 'any';
  98. });
  99. _this.expr = expr;
  100. return _this;
  101. }
  102. (0, _createClass2["default"])(FunctionAssignmentNode, [{
  103. key: "type",
  104. get: function get() {
  105. return name;
  106. }
  107. }, {
  108. key: "isFunctionAssignmentNode",
  109. get: function get() {
  110. return true;
  111. }
  112. /**
  113. * Compile a node into a JavaScript function.
  114. * This basically pre-calculates as much as possible and only leaves open
  115. * calculations which depend on a dynamic scope with variables.
  116. * @param {Object} math Math.js namespace with functions and constants.
  117. * @param {Object} argNames An object with argument names as key and `true`
  118. * as value. Used in the SymbolNode to optimize
  119. * for arguments from user assigned functions
  120. * (see FunctionAssignmentNode) or special symbols
  121. * like `end` (see IndexNode).
  122. * @return {function} Returns a function which can be called like:
  123. * evalNode(scope: Object, args: Object, context: *)
  124. */
  125. }, {
  126. key: "_compile",
  127. value: function _compile(math, argNames) {
  128. var childArgNames = Object.create(argNames);
  129. (0, _array.forEach)(this.params, function (param) {
  130. childArgNames[param] = true;
  131. });
  132. // compile the function expression with the child args
  133. var evalExpr = this.expr._compile(math, childArgNames);
  134. var name = this.name;
  135. var params = this.params;
  136. var signature = (0, _array.join)(this.types, ',');
  137. var syntax = name + '(' + (0, _array.join)(this.params, ', ') + ')';
  138. return function evalFunctionAssignmentNode(scope, args, context) {
  139. var signatures = {};
  140. signatures[signature] = function () {
  141. var childArgs = Object.create(args);
  142. for (var i = 0; i < params.length; i++) {
  143. childArgs[params[i]] = arguments[i];
  144. }
  145. return evalExpr(scope, childArgs, context);
  146. };
  147. var fn = typed(name, signatures);
  148. fn.syntax = syntax;
  149. scope.set(name, fn);
  150. return fn;
  151. };
  152. }
  153. /**
  154. * Execute a callback for each of the child nodes of this node
  155. * @param {function(child: Node, path: string, parent: Node)} callback
  156. */
  157. }, {
  158. key: "forEach",
  159. value: function forEach(callback) {
  160. callback(this.expr, 'expr', this);
  161. }
  162. /**
  163. * Create a new FunctionAssignmentNode whose children are the results of
  164. * calling the provided callback function for each child of the original
  165. * node.
  166. * @param {function(child: Node, path: string, parent: Node): Node} callback
  167. * @returns {FunctionAssignmentNode} Returns a transformed copy of the node
  168. */
  169. }, {
  170. key: "map",
  171. value: function map(callback) {
  172. var expr = this._ifNode(callback(this.expr, 'expr', this));
  173. return new FunctionAssignmentNode(this.name, this.params.slice(0), expr);
  174. }
  175. /**
  176. * Create a clone of this node, a shallow copy
  177. * @return {FunctionAssignmentNode}
  178. */
  179. }, {
  180. key: "clone",
  181. value: function clone() {
  182. return new FunctionAssignmentNode(this.name, this.params.slice(0), this.expr);
  183. }
  184. /**
  185. * get string representation
  186. * @param {Object} options
  187. * @return {string} str
  188. */
  189. }, {
  190. key: "_toString",
  191. value: function _toString(options) {
  192. var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep';
  193. var expr = this.expr.toString(options);
  194. if (needParenthesis(this, parenthesis, options && options.implicit)) {
  195. expr = '(' + expr + ')';
  196. }
  197. return this.name + '(' + this.params.join(', ') + ') = ' + expr;
  198. }
  199. /**
  200. * Get a JSON representation of the node
  201. * @returns {Object}
  202. */
  203. }, {
  204. key: "toJSON",
  205. value: function toJSON() {
  206. var types = this.types;
  207. return {
  208. mathjs: name,
  209. name: this.name,
  210. params: this.params.map(function (param, index) {
  211. return {
  212. name: param,
  213. type: types[index]
  214. };
  215. }),
  216. expr: this.expr
  217. };
  218. }
  219. /**
  220. * Instantiate an FunctionAssignmentNode from its JSON representation
  221. * @param {Object} json
  222. * An object structured like
  223. * ```
  224. * {"mathjs": "FunctionAssignmentNode",
  225. * name: ..., params: ..., expr: ...}
  226. * ```
  227. * where mathjs is optional
  228. * @returns {FunctionAssignmentNode}
  229. */
  230. }, {
  231. key: "toHTML",
  232. value:
  233. /**
  234. * get HTML representation
  235. * @param {Object} options
  236. * @return {string} str
  237. */
  238. function toHTML(options) {
  239. var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep';
  240. var params = [];
  241. for (var i = 0; i < this.params.length; i++) {
  242. params.push('<span class="math-symbol math-parameter">' + (0, _string.escape)(this.params[i]) + '</span>');
  243. }
  244. var expr = this.expr.toHTML(options);
  245. if (needParenthesis(this, parenthesis, options && options.implicit)) {
  246. expr = '<span class="math-parenthesis math-round-parenthesis">(</span>' + expr + '<span class="math-parenthesis math-round-parenthesis">)</span>';
  247. }
  248. 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;
  249. }
  250. /**
  251. * get LaTeX representation
  252. * @param {Object} options
  253. * @return {string} str
  254. */
  255. }, {
  256. key: "_toTex",
  257. value: function _toTex(options) {
  258. var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep';
  259. var expr = this.expr.toTex(options);
  260. if (needParenthesis(this, parenthesis, options && options.implicit)) {
  261. expr = "\\left(".concat(expr, "\\right)");
  262. }
  263. return '\\mathrm{' + this.name + '}\\left(' + this.params.map(_latex.toSymbol).join(',') + '\\right):=' + expr;
  264. }
  265. }], [{
  266. key: "fromJSON",
  267. value: function fromJSON(json) {
  268. return new FunctionAssignmentNode(json.name, json.params, json.expr);
  269. }
  270. }]);
  271. return FunctionAssignmentNode;
  272. }(Node);
  273. (0, _defineProperty2["default"])(FunctionAssignmentNode, "name", name);
  274. return FunctionAssignmentNode;
  275. }, {
  276. isClass: true,
  277. isNode: true
  278. });
  279. exports.createFunctionAssignmentNode = createFunctionAssignmentNode;