Collapse paths that are part of another path.
npm install path-collapse
Import the module (ESM only).
import collapse from 'path-collapse';
The collapse(paths)
function accepts an array of strings (paths) to collapse. It returns a Collapsed
object with the following properties:
roots
- An object with root paths mapped to descendant paths.descendants
- An object with descendant paths mapped to ancestor paths.
Note that absolute and relative paths do not collapse into each other. For consistency, it is advised to resolve all paths into one kind (absolute or relative) before collapsing.
const collapsed = collapse([
'a/b',
'/a/b',
'a/b/c',
'/b',
'a',
'/a/b/c',
'a/b/c/../../b' // resolves to 'a/b'
]);
console.log(collapsed);
// get all root paths
console.log('roots:', Object.keys(collapsed.roots));
// get all descendant paths
console.log('descendants:', Object.keys(collapsed.descendants));
// check if path is a root path
console.log('is a/b root:', 'a/b' in collapsed.roots);
// check if path is a descendant path
console.log('is a/b descendant:', 'a/b' in collapsed.descendants);
{
roots: [Object: null prototype] {
'/a/b': [ '/a/b/c' ],
'/b': [],
a: [ 'a/b', 'a/b/c/../../b', 'a/b/c' ]
},
descendants: [Object: null prototype] {
'/a/b/c': [ '/a/b' ],
'a/b': [ 'a' ],
'a/b/c/../../b': [ 'a' ],
'a/b/c': [ 'a' ]
}
}
roots: [ '/a/b', '/b', 'a' ]
descendants: [ '/a/b/c', 'a/b', 'a/b/c/../../b', 'a/b/c' ]
is a/b root: false
is a/b descendant: true
Licensed under the MIT License.