Skip to content

Instantly share code, notes, and snippets.

@ryanomor
Created June 27, 2018 15:25
Show Gist options
  • Save ryanomor/5087b108c2bda61a181083e50064ca7c to your computer and use it in GitHub Desktop.
Save ryanomor/5087b108c2bda61a181083e50064ca7c to your computer and use it in GitHub Desktop.
Create a function that emulates the '../' function in the command line
let str1 = '/a/b/../foo/.///';
let str2 = '/a/./b/../../c';
let str3 = '/home';
let str4 = '/a/../../../b';
let str5 = '/../';
function changeDirectory(str) {
let result = "",
ignoreChars = ['.', '..', '/', '//', ''],
directoryArr = str.split('/');
for (let ele of directoryArr) {
if (ele === '..') {
result = result.slice(0, result.length -2);
}
if (!ignoreChars.includes(ele)) {
result += ele + '/';
}
}
return '/' + result.slice(0, result.length - 1); //without the trailing slash :)
}
changeDirectory(str1); //returns /a/foo
changeDirectory(str2); //returns /c
changeDirectory(str3); //returns /home
changeDirectory(str4); //returns /b
changeDirectory(str5); //returns /
@ryanomor
Copy link
Author

Change ignoreChars to a Set to make the runtime more efficient

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment