IndexNode.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. "use strict";
  2. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
  3. Object.defineProperty(exports, "__esModule", {
  4. value: true
  5. });
  6. exports.createIndexNode = void 0;
  7. var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
  8. var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
  9. var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
  10. var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
  11. var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));
  12. var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));
  13. var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
  14. var _array = require("../../utils/array.js");
  15. var _customs = require("../../utils/customs.js");
  16. var _factory = require("../../utils/factory.js");
  17. var _is = require("../../utils/is.js");
  18. var _string = require("../../utils/string.js");
  19. 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); }; }
  20. 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; } }
  21. var name = 'IndexNode';
  22. var dependencies = ['Node', 'size'];
  23. var createIndexNode = /* #__PURE__ */(0, _factory.factory)(name, dependencies, function (_ref) {
  24. var Node = _ref.Node,
  25. size = _ref.size;
  26. var IndexNode = /*#__PURE__*/function (_Node) {
  27. (0, _inherits2["default"])(IndexNode, _Node);
  28. var _super = _createSuper(IndexNode);
  29. /**
  30. * @constructor IndexNode
  31. * @extends Node
  32. *
  33. * Describes a subset of a matrix or an object property.
  34. * Cannot be used on its own, needs to be used within an AccessorNode or
  35. * AssignmentNode.
  36. *
  37. * @param {Node[]} dimensions
  38. * @param {boolean} [dotNotation=false]
  39. * Optional property describing whether this index was written using dot
  40. * notation like `a.b`, or using bracket notation like `a["b"]`
  41. * (which is the default). This property is used for string conversion.
  42. */
  43. function IndexNode(dimensions, dotNotation) {
  44. var _this;
  45. (0, _classCallCheck2["default"])(this, IndexNode);
  46. _this = _super.call(this);
  47. _this.dimensions = dimensions;
  48. _this.dotNotation = dotNotation || false;
  49. // validate input
  50. if (!Array.isArray(dimensions) || !dimensions.every(_is.isNode)) {
  51. throw new TypeError('Array containing Nodes expected for parameter "dimensions"');
  52. }
  53. if (_this.dotNotation && !_this.isObjectProperty()) {
  54. throw new Error('dotNotation only applicable for object properties');
  55. }
  56. return _this;
  57. }
  58. (0, _createClass2["default"])(IndexNode, [{
  59. key: "type",
  60. get: function get() {
  61. return name;
  62. }
  63. }, {
  64. key: "isIndexNode",
  65. get: function get() {
  66. return true;
  67. }
  68. /**
  69. * Compile a node into a JavaScript function.
  70. * This basically pre-calculates as much as possible and only leaves open
  71. * calculations which depend on a dynamic scope with variables.
  72. * @param {Object} math Math.js namespace with functions and constants.
  73. * @param {Object} argNames An object with argument names as key and `true`
  74. * as value. Used in the SymbolNode to optimize
  75. * for arguments from user assigned functions
  76. * (see FunctionAssignmentNode) or special symbols
  77. * like `end` (see IndexNode).
  78. * @return {function} Returns a function which can be called like:
  79. * evalNode(scope: Object, args: Object, context: *)
  80. */
  81. }, {
  82. key: "_compile",
  83. value: function _compile(math, argNames) {
  84. // TODO: implement support for bignumber (currently bignumbers are silently
  85. // reduced to numbers when changing the value to zero-based)
  86. // TODO: Optimization: when the range values are ConstantNodes,
  87. // we can beforehand resolve the zero-based value
  88. // optimization for a simple object property
  89. var evalDimensions = (0, _array.map)(this.dimensions, function (dimension, i) {
  90. var needsEnd = dimension.filter(function (node) {
  91. return node.isSymbolNode && node.name === 'end';
  92. }).length > 0;
  93. if (needsEnd) {
  94. // SymbolNode 'end' is used inside the index,
  95. // like in `A[end]` or `A[end - 2]`
  96. var childArgNames = Object.create(argNames);
  97. childArgNames.end = true;
  98. var _evalDimension = dimension._compile(math, childArgNames);
  99. return function evalDimension(scope, args, context) {
  100. if (!(0, _is.isMatrix)(context) && !(0, _is.isArray)(context) && !(0, _is.isString)(context)) {
  101. throw new TypeError('Cannot resolve "end": ' + 'context must be a Matrix, Array, or string but is ' + (0, _is.typeOf)(context));
  102. }
  103. var s = size(context).valueOf();
  104. var childArgs = Object.create(args);
  105. childArgs.end = s[i];
  106. return _evalDimension(scope, childArgs, context);
  107. };
  108. } else {
  109. // SymbolNode `end` not used
  110. return dimension._compile(math, argNames);
  111. }
  112. });
  113. var index = (0, _customs.getSafeProperty)(math, 'index');
  114. return function evalIndexNode(scope, args, context) {
  115. var dimensions = (0, _array.map)(evalDimensions, function (evalDimension) {
  116. return evalDimension(scope, args, context);
  117. });
  118. return index.apply(void 0, (0, _toConsumableArray2["default"])(dimensions));
  119. };
  120. }
  121. /**
  122. * Execute a callback for each of the child nodes of this node
  123. * @param {function(child: Node, path: string, parent: Node)} callback
  124. */
  125. }, {
  126. key: "forEach",
  127. value: function forEach(callback) {
  128. for (var i = 0; i < this.dimensions.length; i++) {
  129. callback(this.dimensions[i], 'dimensions[' + i + ']', this);
  130. }
  131. }
  132. /**
  133. * Create a new IndexNode whose children are the results of calling
  134. * the provided callback function for each child of the original node.
  135. * @param {function(child: Node, path: string, parent: Node): Node} callback
  136. * @returns {IndexNode} Returns a transformed copy of the node
  137. */
  138. }, {
  139. key: "map",
  140. value: function map(callback) {
  141. var dimensions = [];
  142. for (var i = 0; i < this.dimensions.length; i++) {
  143. dimensions[i] = this._ifNode(callback(this.dimensions[i], 'dimensions[' + i + ']', this));
  144. }
  145. return new IndexNode(dimensions, this.dotNotation);
  146. }
  147. /**
  148. * Create a clone of this node, a shallow copy
  149. * @return {IndexNode}
  150. */
  151. }, {
  152. key: "clone",
  153. value: function clone() {
  154. return new IndexNode(this.dimensions.slice(0), this.dotNotation);
  155. }
  156. /**
  157. * Test whether this IndexNode contains a single property name
  158. * @return {boolean}
  159. */
  160. }, {
  161. key: "isObjectProperty",
  162. value: function isObjectProperty() {
  163. return this.dimensions.length === 1 && (0, _is.isConstantNode)(this.dimensions[0]) && typeof this.dimensions[0].value === 'string';
  164. }
  165. /**
  166. * Returns the property name if IndexNode contains a property.
  167. * If not, returns null.
  168. * @return {string | null}
  169. */
  170. }, {
  171. key: "getObjectProperty",
  172. value: function getObjectProperty() {
  173. return this.isObjectProperty() ? this.dimensions[0].value : null;
  174. }
  175. /**
  176. * Get string representation
  177. * @param {Object} options
  178. * @return {string} str
  179. */
  180. }, {
  181. key: "_toString",
  182. value: function _toString(options) {
  183. // format the parameters like "[1, 0:5]"
  184. return this.dotNotation ? '.' + this.getObjectProperty() : '[' + this.dimensions.join(', ') + ']';
  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. dimensions: this.dimensions,
  196. dotNotation: this.dotNotation
  197. };
  198. }
  199. /**
  200. * Instantiate an IndexNode from its JSON representation
  201. * @param {Object} json
  202. * An object structured like
  203. * `{"mathjs": "IndexNode", dimensions: [...], dotNotation: false}`,
  204. * where mathjs is optional
  205. * @returns {IndexNode}
  206. */
  207. }, {
  208. key: "toHTML",
  209. value:
  210. /**
  211. * Get HTML representation
  212. * @param {Object} options
  213. * @return {string} str
  214. */
  215. function toHTML(options) {
  216. // format the parameters like "[1, 0:5]"
  217. var dimensions = [];
  218. for (var i = 0; i < this.dimensions.length; i++) {
  219. dimensions[i] = this.dimensions[i].toHTML();
  220. }
  221. if (this.dotNotation) {
  222. return '<span class="math-operator math-accessor-operator">.</span>' + '<span class="math-symbol math-property">' + (0, _string.escape)(this.getObjectProperty()) + '</span>';
  223. } else {
  224. return '<span class="math-parenthesis math-square-parenthesis">[</span>' + dimensions.join('<span class="math-separator">,</span>') + '<span class="math-parenthesis math-square-parenthesis">]</span>';
  225. }
  226. }
  227. /**
  228. * Get LaTeX representation
  229. * @param {Object} options
  230. * @return {string} str
  231. */
  232. }, {
  233. key: "_toTex",
  234. value: function _toTex(options) {
  235. var dimensions = this.dimensions.map(function (range) {
  236. return range.toTex(options);
  237. });
  238. return this.dotNotation ? '.' + this.getObjectProperty() + '' : '_{' + dimensions.join(',') + '}';
  239. }
  240. }], [{
  241. key: "fromJSON",
  242. value: function fromJSON(json) {
  243. return new IndexNode(json.dimensions, json.dotNotation);
  244. }
  245. }]);
  246. return IndexNode;
  247. }(Node);
  248. (0, _defineProperty2["default"])(IndexNode, "name", name);
  249. return IndexNode;
  250. }, {
  251. isClass: true,
  252. isNode: true
  253. });
  254. exports.createIndexNode = createIndexNode;