Created
June 27, 2018 15:25
-
-
Save ryanomor/5087b108c2bda61a181083e50064ca7c to your computer and use it in GitHub Desktop.
Create a function that emulates the '../' function in the command line
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 / |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Change
ignoreChars
to a Set to make the runtime more efficient