Skip to content

Instantly share code, notes, and snippets.

@brendanashworth
Created April 27, 2015 04:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brendanashworth/91191aeb5ab271e398b7 to your computer and use it in GitHub Desktop.
Save brendanashworth/91191aeb5ab271e398b7 to your computer and use it in GitHub Desktop.
// Licensed io.js code
posix.relative = function(from, to) {
assertPath(from);
assertPath(to);
from = posix.resolve(from).substr(1);
to = posix.resolve(to).substr(1);
function trim(arr) {
var start = 0;
for (; start < arr.length; start++) {
if (arr[start] !== '') break;
}
var end = arr.length - 1;
for (; end >= 0; end--) {
if (arr[end] !== '') break;
}
if (start > end) return [];
return arr.slice(start, end + 1);
}
var fromParts = trim(from.split('/'));
var toParts = trim(to.split('/'));
var length = Math.min(fromParts.length, toParts.length);
var samePartsLength = length;
for (var i = 0; i < length; i++) {
if (fromParts[i] !== toParts[i]) {
samePartsLength = i;
break;
}
}
var outputParts = [];
for (var i = samePartsLength; i < fromParts.length; i++) {
outputParts.push('..');
}
outputParts = outputParts.concat(toParts.slice(samePartsLength));
return outputParts.join('/');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment