Skip to content

Instantly share code, notes, and snippets.

@bruth
Created November 4, 2013 14:31
Show Gist options
  • Save bruth/7303302 to your computer and use it in GitHub Desktop.
Save bruth/7303302 to your computer and use it in GitHub Desktop.
Function to handle joining multiple paths together (behaves like Python's `os.path.join` function). This handles resolving relative and absolute paths, e.g. `['foo/', '.', 'bar/baz/..', 'qux']` => `foo/bar/qux`
joinPath = (paths...) ->
finalPath = []
for path in paths
for tok, i in path.split('/')
switch tok
when '.' then continue
when '..' then finalPath.pop()
else finalPath.push tok
finalPath.join('/')
var joinPath,
__slice = [].slice;
joinPath = function() {
var finalPath, i, path, paths, tok, _i, _j, _len, _len1, _ref;
paths = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
finalPath = [];
for (_i = 0, _len = paths.length; _i < _len; _i++) {
path = paths[_i];
_ref = path.split('/');
for (i = _j = 0, _len1 = _ref.length; _j < _len1; i = ++_j) {
tok = _ref[i];
switch (tok) {
case '.':
continue;
case '..':
finalPath.pop();
break;
default:
finalPath.push(tok);
}
}
}
return finalPath.join('/');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment