Skip to content

Instantly share code, notes, and snippets.

@ericabell
Last active September 13, 2017 21:58
Show Gist options
  • Save ericabell/5b1b3272f2e4943b6089565c0e4eec9d to your computer and use it in GitHub Desktop.
Save ericabell/5b1b3272f2e4943b6089565c0e4eec9d to your computer and use it in GitHub Desktop.
Difference in paths
// Given two absolute paths on a file system, write a function to determine the difference between them.
// For example, `/a/b/c` and `/a/d` should yield `../../d`.
// `/a/b/c` and `/e/f` => `../../../e/f`
// `/` and `/a/b/c` => `/a/b/c`
// `/a/b/c` and `/` => `../../../`
function difference(path1, path2) {
// break the paths into lists and discard the first empty element
path1List = path1.split('/').slice(1);
path2List = path2.split('/').slice(1);
// if path1List's first element is empty, we can just cd into path2
if( path1List[0] === '' ) {
return path2List.join('/');
}
// figure out how deep both paths have in common
// saved as depth
let depth = 0;
for(let i=0; i<path1List.length; i++ ) {
if( path1List[i] != path2List[i] ) {
depth = i;
break;
}
}
// set up returnedPath to contain the return value
let returnedPath = "";
// looping through the number of directories we go need to go up
for(let j=0; j < (path1List.length - depth); j++ ) {
returnedPath += '../'
}
// if path2 doesn't have anything, we can return the path so far
if( path2List[0] === '' ) {
return returnedPath.slice(0,returnedPath.length-1);
}
// descending from our common directory into path2
for(let k=depth; k< path2List.length; k++ ) {
returnedPath += path2List[k] + '/';
}
return returnedPath.slice(0,returnedPath.length-1)
}
console.log('*** TEST CASE 1 ******************');
console.log(difference(`/a/b/c`, `/a/d`)=== `../../d`);
console.log('*** TEST CASE 2 ******************');
console.log(difference(`/a/b/c`, `/e/f`) === `../../../e/f`);
console.log('*** TEST CASE 3 ******************');
console.log(difference(`/`, `/e/f`) === `e/f`);
console.log('*** TEST CASE 4 ******************');
console.log(difference(`/e/f`, `/`) === `../..`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment