Skip to main content

588. Design In-Memory File System

https://leetcode.com/problems/design-in-memory-file-system/

Python

Javascript

 var FileSystem = function() {
this.root = { childs: {} };
};

/**
* @param {string} path
* @return {string[]}
*/
FileSystem.prototype.ls = function(path) {
const node = this.traverse(path);

const ary = [];
if (node.isFile) {
ary.push(node.name);
} else {
for (const key in node.childs) {
const child = node.childs[key];
ary.push(child.name)
}
}
ary.sort();
return ary;
};

/**
* @param {string} path
* @return {void}
*/
FileSystem.prototype.mkdir = function(path) {
this.traverse(path);
};

/**
* @param {string} filePath
* @param {string} content
* @return {void}
*/
FileSystem.prototype.addContentToFile = function(filePath, content) {
const node = this.traverse(filePath)
node.isFile = true;
node.content = (node.content || '') + content;
};

/**
* @param {string} filePath
* @return {string}
*/
FileSystem.prototype.readContentFromFile = function(filePath) {
const node = this.traverse(filePath);
return node.content;

};

FileSystem.prototype.traverse = function(filePath) {
const paths = filePath.split('/')
let node = this.root;
for (let i = 1; i < paths.length; i++) {
const path = paths[i];
if (path) {
if (!node.childs[path]) {
node.childs[path] = { childs: {}, name: path };
}
node = node.childs[path];
}
}
return node;
}