@cloudcome/utils-core
Version:
cloudcome core utils
82 lines (81 loc) • 2.2 kB
JavaScript
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const array = require("./array.cjs");
function _isCurrentSlice(slice) {
return slice === ".";
}
function _isParentSlice(slice) {
return slice === "..";
}
function isAbsolutePath(path) {
return path.startsWith("/");
}
function isRelativePath(path) {
return !isAbsolutePath(path);
}
function pathNormalize(path) {
const slices = path.replace(/\\/g, "/").replace(/\/{2,}/g, "/").replace(/\.{3,}/g, "..").replace(/\/\.\//g, "/").split("/").map((point) => point.trim());
const points = [];
const isAbs = slices[0] === "";
const push = (point) => {
points.push(point);
};
const back = () => {
if (points.length === 1 && isAbs) return;
if (points.length === 0 || points.at(-1) === "..") {
points.push("..");
} else {
points.pop();
}
};
for (const slice of slices) {
const isCurrent = _isCurrentSlice(slice);
const isParent = _isParentSlice(slice);
if (isCurrent) {
continue;
}
if (isParent) {
back();
continue;
}
push(slice);
}
return points.join("/") || (isAbs ? "/" : ".");
}
function pathJoin(from, ...to) {
return pathNormalize([from, ...to].join("/"));
}
function pathResolve(from, ...to) {
const paths = [from, ...to].map(pathNormalize);
let lastStartPath = from;
let lastStartIndex = 0;
array.arrayEach(
paths,
(path, index) => {
if (isAbsolutePath(path)) {
lastStartPath = path;
lastStartIndex = index;
return false;
}
},
true
);
return pathJoin(lastStartPath, ...paths.slice(lastStartIndex + 1));
}
function pathRelativize(path) {
if (isAbsolutePath(path)) return path;
if (path.startsWith("./")) return path;
if (path.startsWith("../")) return path;
return `./${path}`;
}
function pathDirname(path) {
return pathJoin(path, "..");
}
exports.isAbsolutePath = isAbsolutePath;
exports.isRelativePath = isRelativePath;
exports.pathDirname = pathDirname;
exports.pathJoin = pathJoin;
exports.pathNormalize = pathNormalize;
exports.pathRelativize = pathRelativize;
exports.pathResolve = pathResolve;
//# sourceMappingURL=path.cjs.map
;