access.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import { errorTransform } from '../../transform/utils/errorTransform.js';
  2. import { getSafeProperty } from '../../../utils/customs.js';
  3. export function accessFactory(_ref) {
  4. var {
  5. subset
  6. } = _ref;
  7. /**
  8. * Retrieve part of an object:
  9. *
  10. * - Retrieve a property from an object
  11. * - Retrieve a part of a string
  12. * - Retrieve a matrix subset
  13. *
  14. * @param {Object | Array | Matrix | string} object
  15. * @param {Index} index
  16. * @return {Object | Array | Matrix | string} Returns the subset
  17. */
  18. return function access(object, index) {
  19. try {
  20. if (Array.isArray(object)) {
  21. return subset(object, index);
  22. } else if (object && typeof object.subset === 'function') {
  23. // Matrix
  24. return object.subset(index);
  25. } else if (typeof object === 'string') {
  26. // TODO: move getStringSubset into a separate util file, use that
  27. return subset(object, index);
  28. } else if (typeof object === 'object') {
  29. if (!index.isObjectProperty()) {
  30. throw new TypeError('Cannot apply a numeric index as object property');
  31. }
  32. return getSafeProperty(object, index.getObjectProperty());
  33. } else {
  34. throw new TypeError('Cannot apply index: unsupported type of object');
  35. }
  36. } catch (err) {
  37. throw errorTransform(err);
  38. }
  39. };
  40. }