is a commonly used Javascript pattern designed to solve the problem of translating some abstract grammar to code. The common example is JSX, where you define your react code in a XML – like syntax and it gets transformed to Javascript. Babel, Typescript, Dart and other transpilers work similarly.

Doing this by hand is no always the best way, as there are tools to ease the process in great manner.

So let’s try to build a simple textual calculator parser that will have a method that takes a string and a function, representing our grammar and code. After that, all we need is another method that will do some operations based on that grammar and functions. Let’s use some ES6 sugar for this one.

I know it is a simple example, but basically the point here is  to translate your grammar to some code. Oh, and i lied a bit before 🙂 Although the principle is almost the same, Js transpilers mentioned before work with a bit more complexly including creating an abstract syntax tree first. If you want to know more, read this.

Template method

Sometimes, you want to have your behavior defined in your parent / abstract class, letting the subclasses only modify some parts of the process defined. For example, let’s say you are building a beer production line, and want expose only the branding and type of the beer to allow more beer brands to use your production line.

Now for as many different production lines as we need, we have defined the same method for creating our beer, ensuring that the core process is defined in a single spot.

There are numerous applications of this pattern, as it eases the reasoning behind this type of inheritance. Furthermore, you could ensure that your subclasses implement the interface by setting defaults ( in this case brand and contents properties ) to be functions that throw an error.

Chain of responsibility

You know this one if you know how DOM event bubbling works. You click on an element, and if this element has an event listener attached, it will trigger the function provided, if you don’t do e.preventDefault(), the click event is propagated to the wrapping/parent element, checking if the parent has any event listeners setup.

The process goes on until you reach the top of the DOM. To reverse the process, capturing the parent first, you could use the last param in addEventListener function called “usecapture”. One way to this is to create a prototype to share between objects in our chain. The prototype will define that objects in chain hold a reference to the next one, therefore returning the desired value if one of the objects in the chain is able to provide it. Let’s try to implement it with promises, as there the mechanism for creating the chain is already available.

Next, we will see how the Command pattern works, what is the Iterator pattern and what is the difference between Mediator and Facade.