Skip to content

Instantly share code, notes, and snippets.

@rxluz
Created January 19, 2019 02:42
Show Gist options
  • Save rxluz/0617fcee61929bf12227a5df96f98932 to your computer and use it in GitHub Desktop.
Save rxluz/0617fcee61929bf12227a5df96f98932 to your computer and use it in GitHub Desktop.
JS Design Patterns: Composite, see more at: https://medium.com/p/70d274591b11
class Directory {
constructor(name) {
this.setName(name);
this.children = [];
return this;
}
add(element) {
this.children.push(element);
return this;
}
remove(element) {
this.children = this.children.filter(child => child !== element);
return this;
}
getChild(index) {
return this.children[index];
}
setName(name) {
this.name = name;
return this;
}
setContent(content) {
this.content = content;
return this;
}
fill(number, symbol) {
return [...Array(number)].reduce(accummulator => `${accummulator}-`, "");
}
display(level = 0) {
// const test = this.content.map(content => content.display());
const nextLevel = level + 1;
const innerContent = this.children.reduce(
(accummulator, content) =>
`${accummulator} \n ${content.display(nextLevel)}`,
"",
);
return `${this.fill(level, "-")} ${this.name} ${innerContent}`;
}
}
class File {
constructor(name) {
this.setName(name);
}
add() {}
remove() {}
getChild() {}
setName(name) {
this.name = name;
}
fill(number, symbol) {
return [...Array(number)].reduce(accummulator => `${accummulator}-`, "");
}
display(level = 0) {
return `${this.fill(level, "-")} ${this.name}`;
}
}
const run = () => {
const file1 = new File("file 1");
const file2 = new File("file 2");
const file3 = new File("file 3");
const file4 = new File("file 4");
const file5 = new File("file 4");
const subDirectoryWithFile1 = new Directory("subdir1").add(file3);
const subDirectoryWithFile2 = new Directory("subdir2").add(file4).add(file5);
const directoryTree = new Directory("directory1")
.add(file1)
.add(file2)
.add(subDirectoryWithFile1)
.add(subDirectoryWithFile2);
console.log(directoryTree.display());
console.log("****************************************");
directoryTree.remove(file1);
console.log(directoryTree.display());
console.log("**************** WITHOUT subdir1 ************************");
directoryTree.remove(subDirectoryWithFile1);
console.log(directoryTree.display());
};
run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment