Last active
February 10, 2022 19:46
-
-
Save wallace-sf/888eaab7f0458ae1a98210c0a62ac0bd to your computer and use it in GitHub Desktop.
getRelativePath util for lodash `get` function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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