subset.js 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.createSubset = void 0;
  6. var _is = require("../../utils/is.js");
  7. var _object = require("../../utils/object.js");
  8. var _array = require("../../utils/array.js");
  9. var _customs = require("../../utils/customs.js");
  10. var _DimensionError = require("../../error/DimensionError.js");
  11. var _factory = require("../../utils/factory.js");
  12. var name = 'subset';
  13. var dependencies = ['typed', 'matrix'];
  14. var createSubset = /* #__PURE__ */(0, _factory.factory)(name, dependencies, function (_ref) {
  15. var typed = _ref.typed,
  16. matrix = _ref.matrix;
  17. /**
  18. * Get or set a subset of a matrix or string.
  19. *
  20. * Syntax:
  21. * math.subset(value, index) // retrieve a subset
  22. * math.subset(value, index, replacement [, defaultValue]) // replace a subset
  23. *
  24. * Examples:
  25. *
  26. * // get a subset
  27. * const d = [[1, 2], [3, 4]]
  28. * math.subset(d, math.index(1, 0)) // returns 3
  29. * math.subset(d, math.index([0, 1], 1)) // returns [[2], [4]]
  30. *
  31. * // replace a subset
  32. * const e = []
  33. * const f = math.subset(e, math.index(0, [0, 2]), [5, 6]) // f = [[5, 6]] and e = [[5, 0, 6]]
  34. * const g = math.subset(f, math.index(1, 1), 7, 0) // g = [[5, 6], [0, 7]]
  35. *
  36. * // get submatrix using ranges
  37. * const M = [
  38. * [1,2,3],
  39. * [4,5,6],
  40. * [7,8,9]
  41. * ]
  42. * math.subset(M, math.index(math.range(0,2), math.range(0,3))) // [[1,2,3],[4,5,6]]
  43. *
  44. * See also:
  45. *
  46. * size, resize, squeeze, index
  47. *
  48. * @param {Array | Matrix | string} matrix An array, matrix, or string
  49. * @param {Index} index
  50. * For each dimension of the target, specifies an index or a list of
  51. * indices to fetch or set. `subset` uses the cartesian product of
  52. * the indices specified in each dimension.
  53. * @param {*} [replacement] An array, matrix, or scalar.
  54. * If provided, the subset is replaced with replacement.
  55. * If not provided, the subset is returned
  56. * @param {*} [defaultValue=undefined] Default value, filled in on new entries when
  57. * the matrix is resized. If not provided,
  58. * math.matrix elements will be left undefined.
  59. * @return {Array | Matrix | string} Either the retrieved subset or the updated matrix.
  60. */
  61. return typed(name, {
  62. // get subset
  63. 'Array, Index': function ArrayIndex(value, index) {
  64. var m = matrix(value);
  65. var subset = m.subset(index); // returns a Matrix
  66. return index.isScalar() ? subset : subset.valueOf(); // return an Array (like the input)
  67. },
  68. 'Matrix, Index': function MatrixIndex(value, index) {
  69. return value.subset(index);
  70. },
  71. 'Object, Index': _getObjectProperty,
  72. 'string, Index': _getSubstring,
  73. // set subset
  74. 'Array, Index, any': function ArrayIndexAny(value, index, replacement) {
  75. return matrix((0, _object.clone)(value)).subset(index, replacement, undefined).valueOf();
  76. },
  77. 'Array, Index, any, any': function ArrayIndexAnyAny(value, index, replacement, defaultValue) {
  78. return matrix((0, _object.clone)(value)).subset(index, replacement, defaultValue).valueOf();
  79. },
  80. 'Matrix, Index, any': function MatrixIndexAny(value, index, replacement) {
  81. return value.clone().subset(index, replacement);
  82. },
  83. 'Matrix, Index, any, any': function MatrixIndexAnyAny(value, index, replacement, defaultValue) {
  84. return value.clone().subset(index, replacement, defaultValue);
  85. },
  86. 'string, Index, string': _setSubstring,
  87. 'string, Index, string, string': _setSubstring,
  88. 'Object, Index, any': _setObjectProperty
  89. });
  90. });
  91. /**
  92. * Retrieve a subset of a string
  93. * @param {string} str string from which to get a substring
  94. * @param {Index} index An index or list of indices (character positions)
  95. * @returns {string} substring
  96. * @private
  97. */
  98. exports.createSubset = createSubset;
  99. function _getSubstring(str, index) {
  100. if (!(0, _is.isIndex)(index)) {
  101. // TODO: better error message
  102. throw new TypeError('Index expected');
  103. }
  104. if (index.size().length !== 1) {
  105. throw new _DimensionError.DimensionError(index.size().length, 1);
  106. }
  107. // validate whether the range is out of range
  108. var strLen = str.length;
  109. (0, _array.validateIndex)(index.min()[0], strLen);
  110. (0, _array.validateIndex)(index.max()[0], strLen);
  111. var range = index.dimension(0);
  112. var substr = '';
  113. range.forEach(function (v) {
  114. substr += str.charAt(v);
  115. });
  116. return substr;
  117. }
  118. /**
  119. * Replace a substring in a string
  120. * @param {string} str string to be replaced
  121. * @param {Index} index An index or list of indices (character positions)
  122. * @param {string} replacement Replacement string
  123. * @param {string} [defaultValue] Default value to be uses when resizing
  124. * the string. is ' ' by default
  125. * @returns {string} result
  126. * @private
  127. */
  128. function _setSubstring(str, index, replacement, defaultValue) {
  129. if (!index || index.isIndex !== true) {
  130. // TODO: better error message
  131. throw new TypeError('Index expected');
  132. }
  133. if (index.size().length !== 1) {
  134. throw new _DimensionError.DimensionError(index.size().length, 1);
  135. }
  136. if (defaultValue !== undefined) {
  137. if (typeof defaultValue !== 'string' || defaultValue.length !== 1) {
  138. throw new TypeError('Single character expected as defaultValue');
  139. }
  140. } else {
  141. defaultValue = ' ';
  142. }
  143. var range = index.dimension(0);
  144. var len = range.size()[0];
  145. if (len !== replacement.length) {
  146. throw new _DimensionError.DimensionError(range.size()[0], replacement.length);
  147. }
  148. // validate whether the range is out of range
  149. var strLen = str.length;
  150. (0, _array.validateIndex)(index.min()[0]);
  151. (0, _array.validateIndex)(index.max()[0]);
  152. // copy the string into an array with characters
  153. var chars = [];
  154. for (var i = 0; i < strLen; i++) {
  155. chars[i] = str.charAt(i);
  156. }
  157. range.forEach(function (v, i) {
  158. chars[v] = replacement.charAt(i[0]);
  159. });
  160. // initialize undefined characters with a space
  161. if (chars.length > strLen) {
  162. for (var _i = strLen - 1, _len = chars.length; _i < _len; _i++) {
  163. if (!chars[_i]) {
  164. chars[_i] = defaultValue;
  165. }
  166. }
  167. }
  168. return chars.join('');
  169. }
  170. /**
  171. * Retrieve a property from an object
  172. * @param {Object} object
  173. * @param {Index} index
  174. * @return {*} Returns the value of the property
  175. * @private
  176. */
  177. function _getObjectProperty(object, index) {
  178. if (index.size().length !== 1) {
  179. throw new _DimensionError.DimensionError(index.size(), 1);
  180. }
  181. var key = index.dimension(0);
  182. if (typeof key !== 'string') {
  183. throw new TypeError('String expected as index to retrieve an object property');
  184. }
  185. return (0, _customs.getSafeProperty)(object, key);
  186. }
  187. /**
  188. * Set a property on an object
  189. * @param {Object} object
  190. * @param {Index} index
  191. * @param {*} replacement
  192. * @return {*} Returns the updated object
  193. * @private
  194. */
  195. function _setObjectProperty(object, index, replacement) {
  196. if (index.size().length !== 1) {
  197. throw new _DimensionError.DimensionError(index.size(), 1);
  198. }
  199. var key = index.dimension(0);
  200. if (typeof key !== 'string') {
  201. throw new TypeError('String expected as index to retrieve an object property');
  202. }
  203. // clone the object, and apply the property to the clone
  204. var updated = (0, _object.clone)(object);
  205. (0, _customs.setSafeProperty)(updated, key, replacement);
  206. return updated;
  207. }