Last active
September 23, 2019 02:06
-
-
Save TheRealJAG/0acc8b81be8012f14a6b58808a0de26d to your computer and use it in GitHub Desktop.
Write a function that provides change directory (cd) function for an abstract file system.
This file contains 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
<?php | |
class Path { | |
public $currentPath; | |
function __construct($path) { | |
$this->currentPath = $path; | |
} | |
public function cd($newPath) { | |
$innerCounter = 0; | |
$strOut= ''; | |
$newPath = explode('/',$newPath); | |
$oldPath = explode('/', $this->currentPath); | |
foreach($newPath as $str) { | |
echo $str.'<P>'; | |
if($str == '..') $innerCounter++; | |
} | |
$oldLength = count($oldPath); | |
for($i=0;$i<($oldLength - $innerCounter);$i++) | |
$strOut .= $oldPath[$i]."/"; | |
$newLength = count($newPath); | |
for($i=0;$i<$newLength;$i++){ | |
if($newPath[$i] !='..'){ | |
$strOut = $strOut.$newPath[$i].''; | |
} | |
} | |
$this->currentPath = $strOut; | |
return $this; | |
} | |
} | |
$path = new Path('/a/b/c/d'); | |
echo $path->cd('../x')->currentPath; |
I think this might be an approved answer.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
`
class Path
{
public $currentPath;
}
$path = new Path('/a/b/c/d');
$path->cd('../x');
echo $path->currentPath;
`