Skip to content

Instantly share code, notes, and snippets.

@nuintun
Last active December 16, 2022 03:05
Show Gist options
  • Save nuintun/88e56d0dbd18d4f50705e87f30985b18 to your computer and use it in GitHub Desktop.
Save nuintun/88e56d0dbd18d4f50705e87f30985b18 to your computer and use it in GitHub Desktop.
normalize
/**
* @function normalize
* @description Normalize the path.
* @param path The path to normalize.
*/
export function normalize(path: string): string {
if (path === '') return '.';
const parts = path.split(/[\\/]+/);
const { length } = parts;
if (length <= 1) return path;
const segments: string[] = [parts[0]];
const isAbsolute = /^[\\/]/.test(path);
for (let index = 1; index < length; index++) {
const { length } = segments;
const segment = parts[index];
const parent = segments[length - 1];
switch (segment) {
case '.':
break;
case '..':
if (length > 0 && parent !== '..') {
segments.pop();
if (parent === '.') {
segments.push(segment);
}
} else if (!isAbsolute) {
segments.push(segment);
}
break;
default:
if (segment !== '' && parent === '.') {
segments.pop();
}
segments.push(segment);
break;
}
}
return segments.join('/');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment