Last active
January 20, 2022 18:54
-
-
Save Semant1ka/9fa841aea49a0bfd2c29a0b282d9c30f to your computer and use it in GitHub Desktop.
588. Design In-Memory File System
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
from collections import deque | |
class FileObject: | |
def __init__(self, name): | |
self.content = None | |
self.name = name | |
self.children = [] | |
class FileSystem: | |
def __init__(self): | |
# initalize empty directory, aka root directory | |
self.root = FileObject("",) | |
def get_path(self, path): | |
path_list = path.split("/") | |
if not path_list: | |
return [] | |
return path_list[1:] | |
def ls(self, path: str) -> List[str]: | |
path_list = self.get_path(path) | |
if not path_list: | |
return [] | |
current_node = self.root | |
for p in path_list: | |
for child in current_node.children: | |
if child.name == p: | |
current_node = child | |
break | |
return [current_node.name] if current_node.content else sorted([x.name for x in current_node.children]) | |
def get_object(self, path:str) -> FileObject: | |
path_list = self.get_path(path) | |
if not path_list: | |
return [] | |
current_node = self.root | |
for p in path_list: | |
if p not in [x.name for x in current_node.children]: | |
new_directory = FileObject(name=p) | |
current_node.children.append( | |
new_directory | |
) | |
current_node = new_directory | |
else: | |
current_node = next(filter(lambda x: x.name == p, current_node.children), None) | |
return current_node | |
def mkdir(self, path: str) -> None: | |
self.get_object(path) | |
def addContentToFile(self, filePath: str, content: str) -> None: | |
obj = self.get_object(filePath) | |
if obj.content: | |
obj.content += content | |
else: | |
obj.content = content | |
def readContentFromFile(self, filePath: str) -> str: | |
return self.get_object(filePath).content |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment