How to write Wrapper Functions? (aka Decorators)

Wrapping a function, also known Decorating, is parallel to inheriting from an object in the OOP world. It is a way of taking a prototype idea and extend it in a way that encourages code reuse. Moreover, it is a powerful creative tool that open doors to new ways of coding and thinking.

Say we developed a Server that logs many messages like

But it is only after we coded that we realized we forgot to log the actual time of the message. First thing that comes to mind is that the code needs to get refactored, and any appearance of console.log should be replaced with some other function that logs the time as well. This is probably the right thing to do by the way, but for the sake of curiosity wouldn’t it be nice if we could just alter console.log?

Altering console.log

Meet wrapper:

Wrapper is a function that accepts a function as a parameter and returns a function when its done. This makes it a Higher-Order Function, which is the title any function that gets or returns a function earns. The way to use wrapper in our Server is:

console.log = wrapper(console.log);

What just happened here? Lets begin from the right side of the expression, we just sent console.log as a parameter to some wrapper. Wrapper received the function, and in return, it gave back a new function. One that first prints the date, and then invokes the parameter function. The returned function eventually is set back to be console.log itself.

Note the use of console.info in the wrapper. If we used console.log to log the date, it wouldn’t work because by the time it invokes console.log is referring the wrapper, but if the wrapper is within in itself.. it means.. – – – > INFINITY !

Note that the parameter func is accessible inside the new function that is being created, and also available in the time of invoking the inner function (which turns to be console.log). This is due to Closures. In a sentence, any function, at the moment of creation, takes a snapshot of its scope which will remain available at the moment of running. This is called Closure since the scope lives just because it has a reference which is the very function that this scope actually belonged to in first place.

What a closure ūüôā

Read that sentence again.

This concept also gives the opportunity for this freak to actually work:

If you are wondering how to use it, this is the way:

But you can also go straight forward:

Last Note
Wrapping a function doesn’t necessarily have to do with mutating existing functions. We could also use wrapping as a function inheritance technique.

This might actually be a more common way, but I just wanted to show off.

For more info see Decorators.

How to write Pure Functions

A pure function is a function where the return value is only determined by its input values, without observable side effects. This is how functions in math work: Math.cos(x) will, for the same value of x , always return the same result

– Wikipedia

Pure Functions fulfill the KISS principle (Keep It Simple & Stupid), Using them in coding can reduce dramatically the complexity of your code. Basically all one has to do is avoiding 2 main mistakes.

1. Not Ecologic

When a function carry side effects, it may become challenging to predict the outcome of invoking it. In many cases, other team member may use our function, not knowing the side effect that will take place. This can cause much confusion. Iv’e seen functions that carry so many side effects that it was extremely challenging to understand how to maintain them.


// Bad example:
function getNewDog() {

   // Create Dog
   var newDog = DogFactory.createDog("woof!");

   // Add it to Golbal list [not ecologic!]
   owner.dogs.push(newDog);

   // Return the dog
   return newDog;
}

In the example above, the owners’ list is altered because this is the programmer intention. But the function name doesn’t reveal it’s hidden affects. A pure way to write this function would be:


// Good example:
function getNewDog() {

   // Create Dog, and return it
   return DogFactory.createDog("woof!");
}

// Add to list
owner.dogs.push(getNewDog());

2. Not Independent

When the value is not determined only by the parameter, a function might be unpredictable of value. It also might cause Error if it runs in foreign scopes. And on top of that, it limits the function to be too specific to task.


// Bad example:
function getHealthyDog() {

   // For each dog of Global owner [Not Independent]
   for(var dog of owner.dogs) {

     // If the dog is healthy
     if(dog.healthy) {

       // Return it
       return dog;
     }
   }
}

The function above is dependent on owner. If the owner changes, the value of the function changes. If the owner is undefined the function throws error. A Pure way to write it would be:


// Good example:
function getHealthy(list) {

   // For each item in list
   for(var item of list) {

     // If the item is healthy
     if(item.healthy) {

       // Return it
       return item;
     }
   }
}

getHealthy(owner.dogs);

Note that by making the function purer, we enlarged it’s purpose and made it abstract. Now it doesn’t yield a healthy dog, but any object that could be identified as healthy.

Pure functions are easy to learn and adopt. They will make your life easier.

Implementing Language Processing

Intro

When writing crawlers, often I found myself¬†trying to¬†figure out what time was a post written when the String that inserted into the Database¬†was “2 days ago at 16:20”. Thus I implemented its-a-date, ¬†a¬†Natural Language Date Description Processor, or simply – when given a Date description, it returns a Date object.

In the process of figuring out how to approach the implementation of a Date Description Parser, I realized that I have to use the Interpreter Design Pattern, in other words, I had to write a Programming Language. Mostly I learned how to do so from this guy. But this article is a shorter and much simpler version of how to implement a Programming Language as a solution for my problem.

First of all, what is the connection between Date Description and a Programming Language? Well, it seems that date descriptions tend to have pretty accurate syntax. Here are some examples.

3 months after 11/01/1990

Type: Relative
Value: +3 Months

Type: Absolute
(Point of Reference)
Day: 11, Month: 1,
Year: 1990

 

An other example would be:

 

2 days ago at 16:20

Type: Relative
Value: -2 Days

Point of Reference: Now (Default)
Type: Absolute
Hour: 16, Minute: 20

 

2 Different Affect Types: The Relative & The Absolute

It seems that date descriptions can contain two affect types, Relative & Absolute.¬†First one, the Absolute, determines¬†different time parts (e.g ‘Today’ – sets the date, or ‘4th’ sets the day of the month). Relatives indicate a movement in timeline¬†according to a¬†point of reference. Default point of reference would be This Very Moment, but if an Absolute part has been set, usually it turns to be the point of reference. For example ‘in 2 minutes’ refers to 2 minutes from now, but ‘2 minutes after midnight’¬†refers to the hour 00:00.

Note that the scope of an affect type, relative or absolute, is a specific time part. For instance if we take a look at¬†‘Yesterday, 2 minutes after midnight’ ¬†we can see that ‘Yesterday’ is a relative refers to Now, but ‘2 minutes after’ is a relative refers to the Absolute ‘midnight’.¬†

Some regulations must be applied. We can easily see that 2 Absolutes¬†of the same time part are not allowed (e.g. ‘midnight at 2 pm’, two absolute hour affects). On the other hand there is no problem of chaining relatives of the same time part (e.g. ‘2 minutes before 2 minutes before now’,¬†although it’s somewhat silly).

 

Tokens

After discussing the grammar, or the fundamental¬†rules of¬†Date Descriptions, it is time to talk about tokens. Tokens are the tiniest part of a syntax, it’s a Symbol, Word or a¬†Phrase¬†that has a determined¬†action and a specific role in the language. In JavaScript, for instance, some of the tokens are: {, if, new, )¬†&¬†case

In the program, tokens will carry the logic of the Affect Types discussed above. Every token must have a predefined meaning that the interpreter can resolve. Lets review some of its-a-date tokens:

 

febsnip

 

The regex determines whether or not a token is invoked. The Affects is an array of consequences this token is going to carry, in this example, the month time part will be absolutely 2. this may also be the point of reference in case of a description like ‘3 months after February’.

 
 

agotoken

Notice that here we got a token of some other kind. It doesn’t have an Affects array, instead it has an affectGenerator function. The purpose of this function is to return an array of affects, given the values from the regex capturing groups. Notice that not only the value of the relative affect is determined by the matches, also the time type. When the description¬†is “5 days ago”, the day part is altered, but if the description is “5 minutes ago”, the minutes are altered.

 
 

hourtoken

In this token example, we can see the affect generator that we recognize, but the special case here is that a single token have 2 affects. One over the hour, and the second over the minutes.

 

Interpreter

It is time to leave you with the riddle of how to implement the code that translates these tokens, and others, into a date object. If you are eager to fully understand how it actually works, I feel it is best understood when debugging. I welcome you to download the small project from Github, or just hit:
npm install its-a-date --save
and then…

 

itsadate

 

If you feel like contributing to the project, pull requests will make me happy. Implementing tokens for further more foreign languages can be a good practice of this article’s ideas, and as well very¬†appreciated.