JavaScript function to simplify Unix Path !
Автор: Code Canvas
Загружено: 2025-08-11
Просмотров: 47
To simplify a Unix-style absolute file path in JavaScript, you can use a stack-based approach.
This involves splitting the path by `/`, processing each part, and reconstructing the simplified path.
Here's a clear example:
✅ JavaScript Function to Simplify Unix Path
function simplifyPath(path) {
const parts = path.split('/');
const stack = [];
for (const part of parts) {
if (part === '' || part === '.') {
continue; // Skip empty or current directory
} else if (part === '..') {
stack.pop(); // Go up one directory
} else {
stack.push(part); // Valid directory name
}
}
return '/' + stack.join('/');
}
📌 Example Usage
console.log(simplifyPath("/home/")); // Output: "/home"
console.log(simplifyPath("/a/./b/../../c/")); // Output: "/c"
console.log(simplifyPath("/../")); // Output: "/"
console.log(simplifyPath("/home//foo/")); // Output: "/home/foo"
console.log(simplifyPath("/a//b////c/d//././/..")); // Output: "/a/b/c"
🔍 Explanation
`.` means current directory → ignore it.
`..` means go up one level → pop from stack.
Empty strings from multiple slashes `//` → ignore.
Valid directory names → push to stack.
🔔 Subscribe for more videos like this : https://www.youtube.com/c/CodeCanvas?...
#codecanvas #javascript #javascripttutorial
Доступные форматы для скачивания:
Скачать видео mp4
-
Информация по загрузке: