Problem

Given an absolute path for a file (Unix-style), simplify it.

Example

path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
path = "/../", => "/"
path = "/home//foo/", => "/home/foo"

JavaScript Code

function simplifyPath(path) {
    var stack = [];
 
    while(path.length > 0 && path.charAt(path.length-1) =='/'){
        path = path.substring(0, path.length-1);
    }
 
    var start = 0;
    for(var i=1; i<path.length; i++){
        if(path.charAt(i) == '/'){
            stack.push(path.substring(start, i));
            start = i;
        }else if(i==path.length-1){
            stack.push(path.substring(start));
        }
    }
 
    var result = [];
    var back = 0;
    while(stack.length!=0){
        var top = stack.pop();
 
        if(top == "/." || top == "/"){
            //nothing
        }else if(top == "/.."){
            back++;
        }else{
            if(back > 0){
                back--;
            }else{
                result.push(top);
            }
        }
    }
 
    //if empty, return "/"
    if(result.length == 0){
        return "/";
    }
 
    var sb = '';
    while(result.length!=0){
        var s = result.pop();
        sb += s;
    }
 
    return sb;
}

console.log(simplifyPath('/home//foo/'));

0 comments:

Blogroll

Follow this blog by Email

Popular Posts