Challenge: Composite Pattern
In this challenge, you have to implement the composite pattern to solve the given problem.
We'll cover the following
Problem statement
In this challenge, you have to implement a directory system using the composite pattern.
You have been given the following skeleton code:
class Directory{constructor(name,lastModified,size){this.name = namethis.lastModified = lastModifiedthis.size = size}getLastmodified(){}getSize(){}getName(){}}class File extends Directory{}class Folder extends Directory{}
It’s up to you to figure out which class will be the component, leaf subclass, and composite subclass.
A Directory
has the following properties:
-
name
: name of the file/folder. -
lastModified
: time in minutes since the last modification. -
size
: the size of the file/folder in kilobytes.
You have the following functions in the Directory
class:
-
getLastmodified
: Returns thelastModified
time of a file. In the case of a folder with multiple files, it should return the minimum of thelastmodified
times of all files. -
getSize
: Returns thesize
of a file/folder. -
getName
: Returns thename
of the file or all the files in the case of a folder.
The composite subclass should contain the following additional functions as well:
-
addFile
-
removeFile
Input
Calling the given functions on files and folders
Output
The correct output after calling these functions such as lastModified
time, name
and size
Sample input
const file = new File("penguiny.png",6,12)
file.getLastmodified()
file.getName()
file.getSize()
Sample output
6
"penguiny.png"
12
Challenge #
Take a close look and design a step-by-step solution before jumping on to the implementation. This problem is designed for your practice, so try to solve it on your own first. If you get stuck, you can always refer to the solution provided. Good Luck!
//Componentclass Directory{constructor(name,lastModified,size){this.name = namethis.lastModified = lastModifiedthis.size = size}getLastmodified(){}getSize(){}getName(){}}//Leaf subclassclass File extends Directory{}//Compsoite subclassclass Folder extends Directory{}
Let’s discuss the solution in the next lesson.