Last active
December 16, 2022 03:05
-
-
Save nuintun/88e56d0dbd18d4f50705e87f30985b18 to your computer and use it in GitHub Desktop.
normalize
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
/** | |
* @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