Diza Moa
Diza Moa

Reputation: 61

Composite design pattern in Javascript

I wanted to understand more about composite design pattern. I code in JS so I was going through it's example when I stumbled upon this article.

function File(name) {
    this.name = name;
}

File.prototype.display = function () {
    console.log(this.name);
}

function Directory(name) {
    this.name = name;
    this.files = [];
}

Directory.prototype.add = function (file) {
    this.files.push(file);
}

Directory.prototype.remove = function (file) {
    for (let i = 0, length = this.files.length; i < length; i++) {
        if (this.files[i] === file) {
            this.files.splice(i, 1);
            return true;
        }
    }
    
    return false;
}

Directory.prototype.getFileName = function (index) {
    return this.files[index].name;
}

Directory.prototype.display = function() {
    console.log(this.name);
    for (let i = 0, length = this.files.length; i < length; i++) {
        console.log("   ", this.getFileName(i));
    }
}

directoryOne = new Directory('Directory One');
directoryTwo = new Directory('Directory Two');
directoryThree = new Directory('Directory Three');

fileOne = new File('File One');
fileTwo = new File('File Two');
fileThree = new File('File Three');

directoryOne.add(fileOne);
directoryOne.add(fileTwo);

directoryTwo.add(fileOne);

directoryThree.add(fileOne);
directoryThree.add(fileTwo);
directoryThree.add(fileThree);

directoryOne.display();
directoryTwo.display();
directoryThree.display();

From this article

I am still not clear with composite design pattern and would love if someone could explain it to me using the above code snippet.

Upvotes: 1

Views: 304

Answers (1)

Clish
Clish

Reputation: 38

Lets imagine you're writing a js class, the below would be a constructor function


function File(name) {
    this.name = name;
}

to call it you would use const myName = new File('Salim')

The below would be a method in a class, though if there was a method defined inside the class with the same name it would be evaluated instead of this one.

File.prototype.display = function () {
    console.log(this.name);
}

myName.display() would evaluate to Salim. If you understood that, then the rest should be self explanatory. The above can also be rewritten as

class File{
  constructor(name){
     this.name=name
}
 display=()=>{
  console.log(this.name)
 }
}

Upvotes: 1

Related Questions