call(back)
Algorithms & Data StructuresmediumSign in to star problems

In-Memory File System

Build an in-memory file system keyed by slash-separated paths — an object-oriented design exercise where the logic is simple and a clean implementation is the point.

fs.create(path, value?)   // true if created; false if it already exists; throws if the parent is missing
fs.get(path)              // the node's value, or undefined when the path doesn't exist
fs.set(path, value)       // overwrite; throws when the path doesn't exist
fs.list(path = "")        // child names, sorted; [] for a missing path

Paths look like "a/b/c"; leading and trailing slashes are ignored, so "/a/" names the same node as "a". create is mkdir without -p: "a/b" needs "a" to exist first. Every node can hold a value and children.

Hints

Hint 1

One node shape — {children: Map, value} — for everything; the root is a node with no name. Split the path on '/' and drop empty segments so slashes at either end are harmless.

Hint 2

Write one private walk(path) that follows segments and returns the node or null; create, get, set, and list are each a few lines on top of it.

Asked at