AlgorithmsCodilityPatternsTutorials

Composite pattern is one of the most useful, and most used patterns in programming. The basic idea is to make a have a piece of code that treats one object and a group of objects in the same manner. The main blocks on which it operates are composites(a collection of objects, you can think of it as branches), and leafs(the object against which the function is executed )

The main benefit of using this pattern is easier manipulation of large collections of data, because the functions executed on the composite object are passed down to every leaf. This behaviour eases the pain of manipulating large collections, but because of the level of abstraction it is also very easy to forget about performance issues in terms of the shear size of our composite.

Apart from that it organizes the objects into a tree structure, so you can hide the implementation and organize the children in any way you wish.

If you ever used jQuery, you probably noticed that most of its methods work the same if executed against a single, or a collection of elements.You guessed it, jQuery implements the composite pattern on all of its DOM element manipulation methods.

One of the most obvious examples of this hierarchy is the filesystem, so lets try to implement it.

First lets define our files and folders

As you can see, the only difference here is that folder can have children, and file cannot. Lets use that distinction to our advantage for creating a shared prototype for both of them.

Our ‘a’ object should be looking something like this
Capture

Now, lets test our code by executing a function against all of our files that will enlarge them by 50%;

If all went well, all your files should now have a size property!

With slightly different implementations, you can traverse any kind of tree structure and apply your changes to particular nodes, whether composite or leaf.

You can see the benefits of structuring your data like this, as well as traversing it and manipulating it. Tree structures are a science on it’s own, algorithms for optimally manipulating them are an evergreen topic, so be sure to visit my blog often, because after patterns, i will start covering algorithms.

As mentioned earlier, beware of the performance implications of algorithms operating on tree structures, as that can grow to a serious problem.

Next, lets see how decorators work in Javascript.