assign.js 1.6 KB

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