Skip to content

Instantly share code, notes, and snippets.

@andrealaforgia
Created May 6, 2021 10:15
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 andrealaforgia/fd854268c3521e63a012da04891f24cb to your computer and use it in GitHub Desktop.
Save andrealaforgia/fd854268c3521e63a012da04891f24cb to your computer and use it in GitHub Desktop.
package com.company;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Main {
static class FileNode {
final String path;
final FileNode parent;
final Map<String, FileNode> subNodes = new HashMap<>();
FileNode(String path, FileNode parent) {
this.path = path;
this.parent = parent;
}
}
private static FileNode rootDir = new FileNode("/", null);
private static FileNode currentDir = rootDir;
private static void mkdir(String path) {
String _path = path.trim();
var dirs = splitDirs(_path);
if (_path.startsWith("/")) {
makeDirectoriesFrom(rootDir, dirs);
} else {
makeDirectoriesFrom(currentDir, dirs);
}
}
private static void makeDirectoriesFrom(FileNode startDir, List<String> dirs) {
var cursor = startDir;
for (String dir : dirs) {
if (!cursor.subNodes.containsKey(dir)) {
cursor.subNodes.put(dir, new FileNode(cursor.path + dir + "/", cursor));
}
cursor = cursor.subNodes.get(dir);
}
}
private static void navigateDirectoriesFrom(FileNode startDir, List<String> dirs) {
currentDir = startDir;
for (String dir : dirs) {
if (!currentDir.subNodes.containsKey(dir)) {
throw new RuntimeException("Invalid directory: " + dir);
}
currentDir = currentDir.subNodes.get(dir);
}
}
private static void cd(String path) {
String _path = path.trim();
var dirs = splitDirs(_path);
if ("..".equals(_path) && currentDir.parent != null) {
currentDir = currentDir.parent;
} else {
if (_path.startsWith("/")) {
navigateDirectoriesFrom(rootDir, dirs);
} else {
navigateDirectoriesFrom(currentDir, dirs);
}
}
}
private static List<String> splitDirs(String _path) {
return Arrays.stream(_path.split("/")).filter(d -> d.length() > 0).collect(Collectors.toList());
}
private static String pwd() {
return currentDir.path;
}
public static void main(String[] args) {
mkdir("/opt/home");
cd("/opt/home");
System.out.println(pwd());
cd("..");
System.out.println(pwd());
mkdir("app");
cd("app");
System.out.println(pwd());
mkdir("java8");
cd("java8");
System.out.println(pwd());
cd("..");
cd("..");
System.out.println(pwd());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment