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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值