RangeNode.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. "use strict";
  2. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
  3. Object.defineProperty(exports, "__esModule", {
  4. value: true
  5. });
  6. exports.createRangeNode = 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 _factory = require("../../utils/factory.js");
  15. var _operators = require("../operators.js");
  16. 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); }; }
  17. 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; } }
  18. var name = 'RangeNode';
  19. var dependencies = ['Node'];
  20. var createRangeNode = /* #__PURE__ */(0, _factory.factory)(name, dependencies, function (_ref) {
  21. var Node = _ref.Node;
  22. /**
  23. * Calculate the necessary parentheses
  24. * @param {Node} node
  25. * @param {string} parenthesis
  26. * @param {string} implicit
  27. * @return {Object} parentheses
  28. * @private
  29. */
  30. function calculateNecessaryParentheses(node, parenthesis, implicit) {
  31. var precedence = (0, _operators.getPrecedence)(node, parenthesis, implicit);
  32. var parens = {};
  33. var startPrecedence = (0, _operators.getPrecedence)(node.start, parenthesis, implicit);
  34. parens.start = startPrecedence !== null && startPrecedence <= precedence || parenthesis === 'all';
  35. if (node.step) {
  36. var stepPrecedence = (0, _operators.getPrecedence)(node.step, parenthesis, implicit);
  37. parens.step = stepPrecedence !== null && stepPrecedence <= precedence || parenthesis === 'all';
  38. }
  39. var endPrecedence = (0, _operators.getPrecedence)(node.end, parenthesis, implicit);
  40. parens.end = endPrecedence !== null && endPrecedence <= precedence || parenthesis === 'all';
  41. return parens;
  42. }
  43. var RangeNode = /*#__PURE__*/function (_Node) {
  44. (0, _inherits2["default"])(RangeNode, _Node);
  45. var _super = _createSuper(RangeNode);
  46. /**
  47. * @constructor RangeNode
  48. * @extends {Node}
  49. * create a range
  50. * @param {Node} start included lower-bound
  51. * @param {Node} end included upper-bound
  52. * @param {Node} [step] optional step
  53. */
  54. function RangeNode(start, end, step) {
  55. var _this;
  56. (0, _classCallCheck2["default"])(this, RangeNode);
  57. _this = _super.call(this);
  58. // validate inputs
  59. if (!(0, _is.isNode)(start)) throw new TypeError('Node expected');
  60. if (!(0, _is.isNode)(end)) throw new TypeError('Node expected');
  61. if (step && !(0, _is.isNode)(step)) throw new TypeError('Node expected');
  62. if (arguments.length > 3) throw new Error('Too many arguments');
  63. _this.start = start; // included lower-bound
  64. _this.end = end; // included upper-bound
  65. _this.step = step || null; // optional step
  66. return _this;
  67. }
  68. (0, _createClass2["default"])(RangeNode, [{
  69. key: "type",
  70. get: function get() {
  71. return name;
  72. }
  73. }, {
  74. key: "isRangeNode",
  75. get: function get() {
  76. return true;
  77. }
  78. /**
  79. * Check whether the RangeNode needs the `end` symbol to be defined.
  80. * This end is the size of the Matrix in current dimension.
  81. * @return {boolean}
  82. */
  83. }, {
  84. key: "needsEnd",
  85. value: function needsEnd() {
  86. // find all `end` symbols in this RangeNode
  87. var endSymbols = this.filter(function (node) {
  88. return (0, _is.isSymbolNode)(node) && node.name === 'end';
  89. });
  90. return endSymbols.length > 0;
  91. }
  92. /**
  93. * Compile a node into a JavaScript function.
  94. * This basically pre-calculates as much as possible and only leaves open
  95. * calculations which depend on a dynamic scope with variables.
  96. * @param {Object} math Math.js namespace with functions and constants.
  97. * @param {Object} argNames An object with argument names as key and `true`
  98. * as value. Used in the SymbolNode to optimize
  99. * for arguments from user assigned functions
  100. * (see FunctionAssignmentNode) or special symbols
  101. * like `end` (see IndexNode).
  102. * @return {function} Returns a function which can be called like:
  103. * evalNode(scope: Object, args: Object, context: *)
  104. */
  105. }, {
  106. key: "_compile",
  107. value: function _compile(math, argNames) {
  108. var range = math.range;
  109. var evalStart = this.start._compile(math, argNames);
  110. var evalEnd = this.end._compile(math, argNames);
  111. if (this.step) {
  112. var evalStep = this.step._compile(math, argNames);
  113. return function evalRangeNode(scope, args, context) {
  114. return range(evalStart(scope, args, context), evalEnd(scope, args, context), evalStep(scope, args, context));
  115. };
  116. } else {
  117. return function evalRangeNode(scope, args, context) {
  118. return range(evalStart(scope, args, context), evalEnd(scope, args, context));
  119. };
  120. }
  121. }
  122. /**
  123. * Execute a callback for each of the child nodes of this node
  124. * @param {function(child: Node, path: string, parent: Node)} callback
  125. */
  126. }, {
  127. key: "forEach",
  128. value: function forEach(callback) {
  129. callback(this.start, 'start', this);
  130. callback(this.end, 'end', this);
  131. if (this.step) {
  132. callback(this.step, 'step', this);
  133. }
  134. }
  135. /**
  136. * Create a new RangeNode whose children are the results of calling
  137. * the provided callback function for each child of the original node.
  138. * @param {function(child: Node, path: string, parent: Node): Node} callback
  139. * @returns {RangeNode} Returns a transformed copy of the node
  140. */
  141. }, {
  142. key: "map",
  143. value: function map(callback) {
  144. return new RangeNode(this._ifNode(callback(this.start, 'start', this)), this._ifNode(callback(this.end, 'end', this)), this.step && this._ifNode(callback(this.step, 'step', this)));
  145. }
  146. /**
  147. * Create a clone of this node, a shallow copy
  148. * @return {RangeNode}
  149. */
  150. }, {
  151. key: "clone",
  152. value: function clone() {
  153. return new RangeNode(this.start, this.end, this.step && this.step);
  154. }
  155. /**
  156. * Get string representation
  157. * @param {Object} options
  158. * @return {string} str
  159. */
  160. }, {
  161. key: "_toString",
  162. value: function _toString(options) {
  163. var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep';
  164. var parens = calculateNecessaryParentheses(this, parenthesis, options && options.implicit);
  165. // format string as start:step:stop
  166. var str;
  167. var start = this.start.toString(options);
  168. if (parens.start) {
  169. start = '(' + start + ')';
  170. }
  171. str = start;
  172. if (this.step) {
  173. var step = this.step.toString(options);
  174. if (parens.step) {
  175. step = '(' + step + ')';
  176. }
  177. str += ':' + step;
  178. }
  179. var end = this.end.toString(options);
  180. if (parens.end) {
  181. end = '(' + end + ')';
  182. }
  183. str += ':' + end;
  184. return str;
  185. }
  186. /**
  187. * Get a JSON representation of the node
  188. * @returns {Object}
  189. */
  190. }, {
  191. key: "toJSON",
  192. value: function toJSON() {
  193. return {
  194. mathjs: name,
  195. start: this.start,
  196. end: this.end,
  197. step: this.step
  198. };
  199. }
  200. /**
  201. * Instantiate an RangeNode from its JSON representation
  202. * @param {Object} json
  203. * An object structured like
  204. * `{"mathjs": "RangeNode", "start": ..., "end": ..., "step": ...}`,
  205. * where mathjs is optional
  206. * @returns {RangeNode}
  207. */
  208. }, {
  209. key: "toHTML",
  210. value:
  211. /**
  212. * Get HTML representation
  213. * @param {Object} options
  214. * @return {string} str
  215. */
  216. function toHTML(options) {
  217. var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep';
  218. var parens = calculateNecessaryParentheses(this, parenthesis, options && options.implicit);
  219. // format string as start:step:stop
  220. var str;
  221. var start = this.start.toHTML(options);
  222. if (parens.start) {
  223. start = '<span class="math-parenthesis math-round-parenthesis">(</span>' + start + '<span class="math-parenthesis math-round-parenthesis">)</span>';
  224. }
  225. str = start;
  226. if (this.step) {
  227. var step = this.step.toHTML(options);
  228. if (parens.step) {
  229. step = '<span class="math-parenthesis math-round-parenthesis">(</span>' + step + '<span class="math-parenthesis math-round-parenthesis">)</span>';
  230. }
  231. str += '<span class="math-operator math-range-operator">:</span>' + step;
  232. }
  233. var end = this.end.toHTML(options);
  234. if (parens.end) {
  235. end = '<span class="math-parenthesis math-round-parenthesis">(</span>' + end + '<span class="math-parenthesis math-round-parenthesis">)</span>';
  236. }
  237. str += '<span class="math-operator math-range-operator">:</span>' + end;
  238. return str;
  239. }
  240. /**
  241. * Get LaTeX representation
  242. * @params {Object} options
  243. * @return {string} str
  244. */
  245. }, {
  246. key: "_toTex",
  247. value: function _toTex(options) {
  248. var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep';
  249. var parens = calculateNecessaryParentheses(this, parenthesis, options && options.implicit);
  250. var str = this.start.toTex(options);
  251. if (parens.start) {
  252. str = "\\left(".concat(str, "\\right)");
  253. }
  254. if (this.step) {
  255. var step = this.step.toTex(options);
  256. if (parens.step) {
  257. step = "\\left(".concat(step, "\\right)");
  258. }
  259. str += ':' + step;
  260. }
  261. var end = this.end.toTex(options);
  262. if (parens.end) {
  263. end = "\\left(".concat(end, "\\right)");
  264. }
  265. str += ':' + end;
  266. return str;
  267. }
  268. }], [{
  269. key: "fromJSON",
  270. value: function fromJSON(json) {
  271. return new RangeNode(json.start, json.end, json.step);
  272. }
  273. }]);
  274. return RangeNode;
  275. }(Node);
  276. (0, _defineProperty2["default"])(RangeNode, "name", name);
  277. return RangeNode;
  278. }, {
  279. isClass: true,
  280. isNode: true
  281. });
  282. exports.createRangeNode = createRangeNode;