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