Skip to content

Instantly share code, notes, and snippets.

@wallace-sf
Last active February 10, 2022 19:46
Show Gist options
  • Save wallace-sf/888eaab7f0458ae1a98210c0a62ac0bd to your computer and use it in GitHub Desktop.
Save wallace-sf/888eaab7f0458ae1a98210c0a62ac0bd to your computer and use it in GitHub Desktop.
getRelativePath util for lodash `get` function
/**
* @param {string} [path='']
* @return {boolean}
* @author Wallace Ferreira <https://github.com/wallace-sf>
* @example
* isRelativePath('.')
* => true
* isRelativePath('..')
* => true
* isRelativePath('a...')
* => false
* isRelativePath('...c')
* => false
* isRelativePath('a...c')
* => false
*/
const isRelativePath = (path = '') => {
return /^(([.](?=\.))?(\.)+)$/g.test(path);
};
/**
* @description Get a parent path from child path (e.g., `address.street` with part
* `..` should return `address`).
* @param {string} path
* @param {...string} parts
* @return {string} parentPath
* @author Wallace Ferreira <https://github.com/wallace-sf>
* @example
* getParentPath('car.model', 'brand', 'name)
* => 'car.model.brand.name'
* getParentPath('car.model', '.', 'brand', 'name')
* => 'car.model.brand.name'
* getParentPath('car.model', '..', 'brand', 'name')
* => 'car.brand.name'
* getParentPath('car.model', '...', 'brand', 'name')
* => 'brand.name'
* getRelativePath('car.model', '.', 'brand', 'name', '..')
* => 'car.model.brand'
* getParentPath('car.model', '...')
* => ''
*/
export const getRelativePath = (path = '', ...parts) => {
return parts
.reduce((acc, part) => {
if (isRelativePath(part)) {
const endIndexNewPath = acc.length - (part.length - 1);
return acc.slice(0, endIndexNewPath > 0 ? endIndexNewPath : 0);
}
return [...acc, part];
}, path.split('.'))
.join('.');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment