AlgorithmsCodilityPatternsTutorials

Memento serves a simple purpose. If your function does some complex computing, and the same parameters repeat, it is the perfect situation to employ the memento pattern.

You could look at this pattern as if creating your own small database and storing your arguments as a key, and your calculated result as a value. This way, you don’t have to repeat your complex calculation if it has already been calculated, you just simply return the cached value. The calculation must be a pure function, meaning that given the same input(arguments), it will always return the same output.

This pattern is very rare, as often there are many better caching mechanisms available, such as memcached or node-cache. Such libraries provide out of the box handling of these types of situations, as well as cache expiry, so you are probably better of using them.

For an example, we will use a simple addition method naively assuming that our function will only accept numbers. For a more robust approach consider using a real hashing function like object-hash.

The state pattern is a very convenient pattern when your application has a large collection of possible states.

Although at first it might look similar as the chain of responsibility pattern, it servese a different purpose, and is supposed to support circular interchange of states. The most basic example would be a traffic light, changing states from red to yellow to green, and vice versa.

In my implementation, the state holds the logic of which state to transition to, but that need not be so. You could hold all your logic on the state owner, setting the appropriate state from there.

The strategy pattern works very similarly, i’ll explain the difference in that post 🙂

So, let’s build a pub that has 12 hour shifts, and does not work on sundays. For the purpose of this demo, i changed the 12h to 1.2s so you can debug easily, but if you prove to me that you have ran a real simulation for a month, i’ll give you some hats in theme fortress 2.

 

The Visitor pattern is rarely used in Javascript, due to it’s dynamic nature it is often far more better to extend the object at runtime with new methods. But never the less, the visitor pattern is one of the original GOF patterns, and i’ts understanding can come useful sometimes.

The idea behind this pattern is to have a method on an object, that accepts a function as i’ts argument, and calls that function with an instance of the object as an argument. Let’s have a look.

I know this looks as an overkill, as we could easily have changed the method without employing the visitor here, but using this pattern you can change the internal and private variables by exposing them through this little trick here

self in this case could have been any object, and the pattern will work as long as it’s arguments are passed by reference.

Next, let’s take a look at the Strategy pattern.