assign.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. "use strict";
  2. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
  3. Object.defineProperty(exports, "__esModule", {
  4. value: true
  5. });
  6. exports.assignFactory = assignFactory;
  7. var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
  8. var _errorTransform = require("../../transform/utils/errorTransform.js");
  9. var _customs = require("../../../utils/customs.js");
  10. function assignFactory(_ref) {
  11. var subset = _ref.subset,
  12. matrix = _ref.matrix;
  13. /**
  14. * Replace part of an object:
  15. *
  16. * - Assign a property to an object
  17. * - Replace a part of a string
  18. * - Replace a matrix subset
  19. *
  20. * @param {Object | Array | Matrix | string} object
  21. * @param {Index} index
  22. * @param {*} value
  23. * @return {Object | Array | Matrix | string} Returns the original object
  24. * except in case of a string
  25. */
  26. // TODO: change assign to return the value instead of the object
  27. return function assign(object, index, value) {
  28. try {
  29. if (Array.isArray(object)) {
  30. // we use matrix.subset here instead of the function subset because we must not clone the contents
  31. return matrix(object).subset(index, value).valueOf();
  32. } else if (object && typeof object.subset === 'function') {
  33. // Matrix
  34. return object.subset(index, value);
  35. } else if (typeof object === 'string') {
  36. // TODO: move setStringSubset into a separate util file, use that
  37. return subset(object, index, value);
  38. } else if ((0, _typeof2["default"])(object) === 'object') {
  39. if (!index.isObjectProperty()) {
  40. throw TypeError('Cannot apply a numeric index as object property');
  41. }
  42. (0, _customs.setSafeProperty)(object, index.getObjectProperty(), value);
  43. return object;
  44. } else {
  45. throw new TypeError('Cannot apply index: unsupported type of object');
  46. }
  47. } catch (err) {
  48. throw (0, _errorTransform.errorTransform)(err);
  49. }
  50. };
  51. }