Skip to content

Instantly share code, notes, and snippets.

@zzuhan
Last active January 4, 2016 08:09
Show Gist options
  • Save zzuhan/8593356 to your computer and use it in GitHub Desktop.
Save zzuhan/8593356 to your computer and use it in GitHub Desktop.
js 的路径处理函数集合
function join(from, to) {
var part, newPath;
isAbsolute = from.charAt(0) == '/',
pathParts = [].concat(from.split('/')).concat(to.split('/')),
finalParts = [],
skipNum = 0;
while( part = pathParts.pop()){
if(part !== '..' && part !== '.') {
if(skipNum) {
skipNum--;
continue;
}
finalParts.unshift(part);
} else {
skipNum += part.length;
}
}
newPath = finalParts.join('/');
if(isAbsolute) newPath = '/' + newPath;
return newPath;
}
// Example
var mod2Id = join('ctrl/mod1', './mod2');
var utilId = join('common/moment', '../util');
console.log(mod2Id); // ctrl/util
console.log(utilId); // util
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment