@stryke/path
Version:
A package containing various utilities that expand the functionality of NodeJs's built-in `path` module
66 lines (64 loc) • 2.19 kB
JavaScript
import { slash } from "./slash.mjs";
import { correctPath, stripStars, withoutTrailingSlash } from "./correct-path.mjs";
import { isSetString } from "@stryke/type-checks/is-set-string";
//#region src/common.ts
/**
* Get the common path from an array of paths
*
* @example
* ```ts
* commonPath(['/foo/bar/baz', '/foo/bar/qux', '/foo/bar/baz/quux']);
* // returns '/foo/bar'
*
* commonPath(['C:/foo/bar/baz', 'C:/foo/bar/qux', 'C:/foo/bar/baz/quux']);
* // returns 'C:/foo/bar'
* ```
*
* @param paths - The array of paths
* @returns The common path
*/
function commonPath(paths) {
const [first = "", ...remaining] = paths.map((path) => correctPath(slash(path)));
if (!first) return "";
if (remaining.length === 0) return first;
let endOfPrefix = first.split("/").length;
for (const path of remaining) {
const compare = path.split("/");
for (let i = 0; i < endOfPrefix; i++) if (compare[i] !== first.split("/")[i]) endOfPrefix = i;
if (endOfPrefix === 0) return "";
}
return withoutTrailingSlash(first.split("/").slice(0, endOfPrefix).join("/"));
}
const findCommonPath = commonPath;
/**
* Find the base path from a string path/glob or an array of string paths/globs. If a string is provided, it is returned as the base path. If an array of strings is provided, the common path among them is returned. If the input is invalid or empty, "/" is returned.
*
* @example
* ```ts
* findBasePath('/foo/bar/baz');
* // returns '/foo/bar/baz'
*
* findBasePath(['/foo/bar/baz', '/foo/bar/qux', '/foo/bar/baz/quux']);
* // returns '/foo/bar'
*
* findBasePath(['C:/foo/bar/baz', 'C:/foo/bar/qux', 'C:/foo/bar/baz/quux']);
* // returns 'C:/foo/bar'
*
* findBasePath(['foo/bar/**\/baz', 'foo/bar/qux/*', 'foo/bar/baz/quux']);
* // returns 'foo/bar'
*
* findBasePath([]);
* // returns '/'
* ```
*
* @param paths - The string or array of strings to find the base path from
* @returns The base path
*/
function findBasePath(paths) {
if (isSetString(paths)) return paths;
else if (Array.isArray(paths) && paths.length > 0) return commonPath(paths.map((path) => stripStars(path)));
return "/";
}
//#endregion
export { commonPath, findBasePath, findCommonPath };
//# sourceMappingURL=common.mjs.map