Saturday, 27 June 2015

Simulating await with ES6 Generators

When I first read about ES6 generators I wrote a post about its differences with C# "iterators" (I'll say it again, horrible naming choice by Microsoft). At that time I read how people were taking advantage of them to write code resembling C#s async/await magic. It seemed hard and interesting to me to understand at first sight how both things were related, but I had no time to look into it at that time. These days, after glancing through this thorough and brilliant article I decided to try to understand it.

The first point to consider is that as mentioned in the article, generator objects created by a generator function implement 2 different interfaces: data producers (iterators, the Symbol.iterator thing), that's what you are used to in C#, and data consumers. The latter is pretty interesting as it's the feature that makes the await emulation possible.

The fundamental idea is that generator objects combine the producer and consumer role in a "next" method that receives a value and returns a value. You represent it like this in your generator function:

var b = yield a;

The essential part in that line is that it really means this:

return a to the current "next" call;
read b from the next "next" call;
and execute the following lines until the next "yield" is found and you return a new value from there);

between both actions, the generator function gets "suspended".

This idea of having your code inside a sort of function (in the end it's a kind of illusion, that function is bended by the compiler into a generator object where state is maintained so that this suspension/reentrancy can really work) is the basis of how async/await works in C#. So, if you return from your yield a sort of Task object that when completed would call the reentrant function again passing it its return value, you basically get the same. Calling the reentrant funtion means calling the generator.next from an async loop, so your Task objects will need a reference to the async loop function (that you will call from the continuation (nextStep property in my example) that you have added to the Task), so that they can continue the cycle.

The JavaScript kind of equivalent to C# Tasks are Promises, and it's what is used by the different libraries (like co) enabling this sort of async/await programming. For exploratory reasons, in order to fully understand this whole thing, when writing my "async/await enabling" function, I've decided to use a very basic TaskInfo object rather than Promises, I think it makes easier to understand how the whole think works with no need to know anything about promises. Indeed, seems like co also works with a sort of lightweight alternative to promises called thunks

I've put up the code in this gist.

Sunday, 21 June 2015

OrderBy vs Max

Some days ago I came across a piece of code by one colleague that caught me quite by surprise. He told me it was a performance improvement, and while in that case it was rather unnecessary and made the code less straight forward, it's good to have it in mind for other occasions. The idea is pretty basic, but I had never though about it before.

The example was in C# and Linq To Objects, so I'll stick to it, but it would be the same with JavaScript and underscore.js or whatever.

So we have a collections of City objects like these:

public class City
{
 public string Name {get; set;}
 public int Population {get; set;}
}

var cities = new List(){
   new City(){
    Name = "Xixon",
    Population = 275000
   },
   new City(){
    Name = "Berlin",
    Population = 4000000
   },
   new City(){
    Name = "Toulouse",
    Population = 1250000
   },
   new City(){
    Name = "Paris",
    Population = 12000000
   }
  };

and we want to get the most populated city. So I would just do this:

biggestCity = cities.OrderByDescending(city => city.Population).First();

while my colleage had written this:

var maxPopulation = cities.Max(city => city.Population);
var biggestCity = cities.First(city => city.Population == maxPopulation);

In the first code, regardless of the sorting algorithm used by OrderBy, we can say that you are finding the Max element n times (each time in a smaller collection), while in the second example you are finding that Max only once. Depending on the Sorting algorithm the first case will usually be O(n*log n), while the second case is O(n). As explained here, apart from the speed improvements, with the OrderBy approach you'll run into an Out of Memory exception if your collection is huge enough.

Saturday, 13 June 2015

The void Operator in JavaScript

The other day, while checking the source of underscore.js (I already mentioned time ago that it was a really beautiful code to learn from) it came to my attention some code like this:

return obj == null ? void 0 : obj[key];

That void operator, what is it useful for? (both in general and in this particular case). Checking in MDN, for this particular use you'll find this:

The void operator is often used merely to obtain the undefined primitive value, usually using "void(0)" (which is equivalent to "void 0"). In these cases, the global variable undefined can be used instead (assuming it has not been assigned to a non-default value).

So it's being used to safely assign the undefined value. "safely" means that when we use undefined this way: obj = undefined; you are using the undefined global property, that by default points to the undefined value, but that someone could have changed assigning it another value and breaking your code!

However, if you run this code in firebug:

var a = undefined;
undefined
a === undefined;
true
undefined = "xxx";
"xxx"
a === undefined;
true

You'll see that indeed the attempt to change the value of the undefined property has not worked! As usual, MDN has the explanation:

undefined is a property of the global object, i.e. it is a variable in global scope. The initial value of undefined is the primitive value undefined.
In modern browsers (JavaScript 1.8.5 / Firefox 4+), undefined is a non-configurable, non-writable property per the ECMAScript 5 specification. Even when this is not the case, avoid overriding it.

The reference for the void operator mentions another use case that really confused me:

When using an immediately-invoked function expression, void can be used to force the function keyword to be treated as an expression instead of a declaration.

So they propose creating IIFS's like this: void function(){}();
I see no use at all in creating an IIFE like that. I pretty much prefer the "normal style":
(function(){}());
or
(function(){})();
Using void adds nothing other than confusion and it looks to me as if we were in another language declaring that the function returns nothing.

Trying to understand if I were missing something with this I checked what seems to be the seminal article about IIFE's. There the author mentions some other utterly confusing ways to declare a IIFE, like these:

// If you don't care about the return value, or the possibility of making
// your code slightly harder to read, you can save a byte by just prefixing
// the function with a unary operator.
!function(){ /* code */ }();
~function(){ /* code */ }();
-function(){ /* code */ }();
+function(){ /* code */ }();

As the author says, it makes the code harder to read, for sure. I love how expressive and freak javascript is, but things like this seem utterly unnecessary to me.

Sunday, 7 June 2015

International Brigades 2.0

Volunteers have been joining the fight against the Fascist Beasts of ISIS in Syria and Irak since last summer. First volunteers came from USA and UK mainly, some of them had militar experience and were joining the battle in a Good vs Evil basis, to defend ordinary men and women from being decapitated, raped, tortured and sold as slaves by the Islamist terrorists. Most of them did not have a left wing ideology, and indeed some of them ended up not feeling comfortable being integrated in a left wing force like YPG-JPG and decided to move to other "not red" groups, like some Christian militias or the Peshmerga.

Since the MLKP (a communist Turkish-Kurdish revolutionary vanguard) made a call to join an International Brigade to fight against IslamoFascism and support the Social Revolution in Rojava, a new kind of western volunteers showed up, these ones with a clear left or far-left ideology. It's unknown how many foreigners make up the ranks of this left wing militia (notice that most foreign revolutionaries there are Turkish-Kurdish Communists and Anarchists), but for sure they have had a certain media impact, and have helped a lot to bring to the table of the European left the drama of the Kurdish people and the need of Antifascists to confront IslamoFascism in the same way they confront "White-Nationalist-Fascism".
I already talked about the German revolutionary Ivana Hoffman, sadly fallen in combat against the IslamoFascist scum, and already in February a video was released portraying 2 Spanish Revolutionaries in Rojava, along with German and Turkish ones.

I had not known much of these humanitarian fighters until today, when through the site of the Comite de Solidaridad con Rojava y el Pueblo Kurdo I've found this documentary by a Spanish TV Channel about the Spanish Revolutionaries there. Unfortunately it is in Spanish, but even if you can not understand the language, the images are well worth your time. From this video I learnt that these Spanish guys are members of the Marxist-Leninist organization Reconstruccion Comunista (Communist Reconstruction) a very militant group putting a huge emphasis in the political education of its members. Knowing this, it's clear that these guys have not been drawn into this battle just for a quest of adventure or a youngster impulse, I assume that they are educated left wing militants taking a reasoned and consequent decision. They had previously done some interesting declarations to other Spanish media. As I'm linking an article in "El Pais" I need to clarify that I feel rather little respect for this Paper. It has its own agenda dictated by Spanish oligarchy, which makes it painfully partial when dealing for example with topics related to South America (Venezuela, Cuba) where this oligarchy has neocolonial interests and attitudes. In no way can it be considered at the level of European real papers like "Le Monde".

This is not a fight against Islam, but for peaceful co-existence between different cultures, and not just in favor of the Kurds, but all humanity. We cannot accept simplistic arguments that Islam is to blame. We are not fighting against Muslims, but against the fascism that Islamic State represents, in the same way that people fought in Spain in 1936 or in Stalingrad in 1943.”

By the way, these pictures of their organization, Reconstruction Comunista, quite impressed me. I'm quite far from some of their political positions, as the concept of "class war" is now totally alien to someone like me that to a certain extent has ended up in the moderate, "System changing but not System breaking" left, but the way they parade through the streets of Madrid, baring communist and republican flags in an almost military formation is really captivating. It gives a sense of discipline, organization, power and willingness to fight that is now more necessary than ever. At these times when the fascist monsters carrying the poison of radical islam or xenophobia and racism are more alive than ever in our old continent, the left must be ready for confrontation, a confrontation that goes far beyond dialectic and keyboards.

Honor and glory to Antifascist fighters