Skip to content

Instantly share code, notes, and snippets.

@Semant1ka
Last active January 20, 2022 18:54
Show Gist options
  • Save Semant1ka/9fa841aea49a0bfd2c29a0b282d9c30f to your computer and use it in GitHub Desktop.
Save Semant1ka/9fa841aea49a0bfd2c29a0b282d9c30f to your computer and use it in GitHub Desktop.
588. Design In-Memory File System
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