UNPKG

@bespunky/angular-zen

Version:

The Angular tools you always wished were there.

53 lines (50 loc) 1.98 kB
function isArrayIndexer(path) { const numericIndexerRegex = /^\w+\[\d+\]$/; return numericIndexerRegex.test(path); } function accessArrayProperty(value, arrayPath) { if (!value) throw new Error(`Cannot access ${arrayPath}. 'value' is ${value}`); if (typeof value !== 'object') throw new Error(`Cannot access ${arrayPath}. ${value} is not an object.`); const pathRegex = /^(?<property>(\w+))\[(?<index>(\d+))\]$/; const lookup = pathRegex.exec(arrayPath)?.groups; if (!(lookup && lookup['property'] && lookup['index'])) throw new Error(` Tried to access array on at '${arrayPath}', but the path is invalid. Expected a path of the shape 'propertyName[index].' `); const { property, index } = lookup; const array = value[property]; if (!Array.isArray(array)) throw new TypeError(`Array property access failed. Value at '${property}' is not an array.`); return { get: () => array[+index], set: (newValue) => array[+index] = newValue }; } function access(value, path) { if (!path) return { get: () => value, set: () => void 0 }; const parts = path.split('.').filter(part => part !== ''); while (parts.length > 1) { const nextPath = parts.shift(); if (typeof value !== 'object') throw new Error(``); value = (isArrayIndexer(nextPath) ? accessArrayProperty(value, nextPath).get() : value[nextPath]); } const lastPath = parts.shift(); return { get: isArrayIndexer(lastPath) ? () => accessArrayProperty(value, lastPath).get() : () => value[lastPath], set: isArrayIndexer(lastPath) ? (newValue) => accessArrayProperty(value, lastPath).set(newValue) : (newValue) => value[lastPath] = newValue }; } /** * Generated bundle index. Do not edit. */ export { access }; //# sourceMappingURL=bespunky-angular-zen-utils.mjs.map