JavaScript path merge
1977 ワード
ルビーソースから翻訳された
function split_path(path){
return path.split(/\/+/);
}
function merge_path(base,rel){
// RFC2396, Section 5.2, 5)
if (rel[0] == '#'){
// RFC2396, Section 5.2, 5)
return rel;
}
// RFC2396, Section 5.2, 6)
var base_path = split_path(base);
var rel_path = split_path(rel);
// RFC2396, Section 5.2, 6), a)
if(base_path[base_path.length-1] == '..'){
base_path.push('');
}
var i;
while ((i = base_path.indexOf('..'))+1){
base_path = base_path.slice(i - 1, 2);
}
if (base_path.length == 0){
base_path = ['']; // keep '/' for root directory
}else{
base_path.pop();
}
// RFC2396, Section 5.2, 6), c)
// RFC2396, Section 5.2, 6), d)
if (rel_path[rel_path.length-1] == '.' || rel_path[rel_path.length-1] == '..'){
rel_path.push('');
}
var old_rel_path = rel_path;
rel_path = [];
for(var i=0,l=old_rel_path.length;i<l;i++){
if(old_rel_path[i]!='.'){
rel_path.push(old_rel_path[i]);
}
}
// RFC2396, Section 5.2, 6), e)
var tmp = []
for(var i=0,l=rel_path.length;i<l;i++){
var x = rel_path[i];
if ( x == '..' && !(tmp.length == 0 || tmp[tmp.length-1]=='..')){
tmp.pop();
}else{
tmp.push(x);
}
}
var add_trailer_slash = true;
var x;
while (x = tmp.shift()){
if (x == '..' && base_path.length > 1){
// RFC2396, Section 4
// a .. or . in an absolute path has no special meaning
base_path.pop();
}else{
base_path.push(x);
for(var i=0,l=tmp.length;i<l;i++){
var t=tmp[i];
base_path.push(t);
}
add_trailer_slash = false;
break;
}
}
if (add_trailer_slash){
base_path.push('') ;
}
return base_path.join('/')
}
//merge_path("/abc/def/gy","./dde")