Facebook Pixel

Exercise: Composite

This exercise puts the Composite pattern into code.

Scenario

A file-system tree holds two kinds of nodes: files and directories. A file's size is fixed. A directory's size is the sum of all its children — which may themselves be directories. The tree starts with an implicit directory named "root". All names in the tree are unique.

Commands

CommandBehaviorOutput
["mkdir", name, parent]Create a directory named name inside parent(none)
["file", name, parent, size]Create a file named name with the given integer size inside parent(none)
["size", name]Report the total size under name"<name>: <total size>", or "<name> not found"
Example
Input
6
mkdir docs root
file readme.md docs 400
file guide.md docs 600
size docs
size root
size missing
Output
docs: 1000
root: 1000
missing not found
Explanation
A `docs` directory is created inside `root`, then two files totalling 1000 bytes are added to it. Querying `docs` returns 1000 — the sum of its children. Querying `root` also returns 1000 because `docs` is its only child and the recursion propagates up. Querying `missing` demonstrates the "not found" case: a name that was never created returns the error message rather than a size.

Your task

Create the two concrete node classes used by the dispatcher below the Node abstract class in the editor: File(Node) with a size() that returns its stored byte count, and Directory(Node) with an add(node) method and a size() that sums children recursively. Do not modify Node or run_filesystem.

Invest in Yourself
Your new job is waiting. 83% of people that complete the program get a job offer. Unlock unlimited access to all content and features.
Go Pro