`
bellstar
  • 浏览: 148477 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

JavaScript path merge

阅读更多

从Ruby源代码翻译过来的

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")

 

分享到:
评论
2 楼 bellstar 2009-01-15  
jindw 写道

一目十行,不知所云,呵呵可以解释一下什么意思吗?没搞过ruby,呵呵,不知道它完成了那些功能?

这是javascript,功能就是参照一个绝对地址求另一个相对地址的绝对地址,
merge_path(绝对地址,相对地址)
1 楼 jindw 2009-01-15  
一目十行,不知所云,呵呵

可以解释一下什么意思吗?
没搞过ruby,呵呵,不知道它完成了那些功能?

相关推荐

Global site tag (gtag.js) - Google Analytics