class FileNode {
constructor(type) {
this.type = type
this.children = {}
}
}
class FileSystem {
constructor() {
this.root = new FileNode('dir')
this.currentPath = this.root;
this.pathStack = ['/'];
}
#traverse(path) {
const parts = path.split('/').filter(Boolean);
let node = this.root;
for (const part of parts) {
if (!node.children[part] || node.children[part].type !== 'dir') {
throw new Error(`Directory '${part}' does not exist`);
}
node = node.children[part];
}
return node;
}
mkdir(path) {
const parts = path.split('/').filter(Boolean);
let node = this.root;
for (const part of parts) {
if (!node.children[part]) {
node.children[part] = new FileNode('dir');
}
node = node.children[part];
if (node.type !== 'dir') {
throw new Error(`${part} is a file, cannot create directory here`);
}
}
}
touch(path) {
const parts = path.split('/').filter(Boolean);
const fileName = parts.pop();
let node = this.root;
for (const part of parts) {
if (!node.children[part] || node.children[part].type !== 'dir') {
throw new Error(`Directory '${part}' does not exist`);
}
node = node.children[part];
}
node.children[fileName] = new FileNode('file')
}
ls(path = '') {
const node = path ? this.#traverse(path) : this.currentPath;
if (node.type !== 'dir') {
throw new Error(`${path} is not a directory`);
}
return Object.keys(node.children);
}
cd(path) {
if (path === '/') {
this.currentPath = this.root;
this.pathStack = ['/'];
return;
}
const node = this.#traverse(path);
this.currentPath = node;
this.pathStack = path.split('/').filter(Boolean);
}
pwd() {
return '/' + this.pathStack.join('/');
}
}
const fs = new FileSystem();
fs.mkdir('/home/user/documents');
fs.mkdir('/home/user/photos');
fs.touch('/home/user/documents/resume.pdf');
fs.touch('/home/user/photos/selfie.png');
console.log(fs.ls('/home/user'));
console.log(fs.ls('/home/user/documents'));
fs.cd('/home/user/documents');
console.log(fs.pwd());
fs.cd('/');
console.log(fs.pwd());