In Memory File System
function FileSystem() {
let root = {};
let currentDir = root;
let currentDirPath = "root";
function mkdir(dir) {
if (!dir) {
throw new Error("Please provide a name to the directory.");
}
if (Object.keys(currentDir).includes(dir)) {
throw new Error("Directory with this name already exist.");
}
currentDir[dir] = {};
}
function cd(path) {
if (path === "..") {
currentDir = root;
currentDirPath = "root";
return;
}
const paths = path.split("/");
paths.forEach((p) => {
if (!currentDir[p]) {
throw new Error("Provided folder path doesnot exist.");
}
currentDir = currentDir[p];
});
currentDirPath = path;
}
function addFile(fileName) {
if (!currentDir.files) {
currentDir.files = [];
}
if (fileName !== "") {
currentDir.files.push(fileName);
}
}
function deleteFile(deleteFile) {
currentDir.files = currentDir.files.filter((file) => file != deleteFile);
}
function deleteDirectory(dir) {
if (!Object.keys(currentDir).includes(dir)) {
throw new Error("No directory exist with this name.");
}
delete currentDir[dir];
}
function getRootDirectory() {
console.log(root);
}
function ls() {
console.log(currentDir);
}
function pwd() {
console.log(currentDirPath);
}
return {
mkdir,
cd,
addFile,
deleteFile,
deleteDirectory,
getRootDirectory,
ls,
pwd,
};
}
const dir = new FileSystem();
dir.mkdir("Arjunan");
dir.cd("Arjunan");
dir.addFile("index.html");
dir.addFile("app.js");
dir.addFile("style.css");
dir.deleteFile("style.css");
dir.ls();
dir.pwd();
dir.cd("..");
dir.mkdir("practice");
dir.cd("practice");
dir.addFile("style.css");
dir.addFile("app.js");
dir.mkdir("build");
dir.cd("build");
dir.mkdir("new");
dir.cd("..");
dir.cd("practice/build/new");
dir.addFile("a.png");
dir.addFile("b.jpg");
dir.deleteFile("a.png");
dir.ls();
dir.pwd();
dir.cd("..");
dir.mkdir("dummy");
dir.deleteDirectory("dummy");
dir.getRootDirectory();
// Output:
{
files: ["index.html", "app.js"],
}
// Arjunan
{
files: ["b.jpg"],
}
// practice/build/new
{
Arjunan: {
files: ["index.html", "app.js"],
},
practice: {
files: ["style.css", "app.js"],
build: {
new: {
files: ["b.jpg"],
},
},
},
};