Saturday, 13 July 2019

Arrow Functions and binding

When doing some tests with Jasmine I wanted to spy on one method invoked from the constructor (I mean method and constructor of the same class). As you need to set the spy before having the instance created, you'll have to spy on the class method (so you'll end up spying on each instance of the class, not just a particular one), not on the instance method. As you know, JavaScript classes are syntax sugar on top of the prototypes mechanism. Apart from "recording" the call, I did not want to invoke the original method, but a function assigning some mock data to one property of the object. So I was setting my spy like this

spyOn(MyClass.prototype, "myMethod").and.callFake(() => this.items = mockData.items);

let myInstance = new MyClass();
console.log(myInstance.items); //undefined!

I had read that the function provided to callFake would receive as this the object on which we are spying, but the above code was not setting the property. Can you spot the problem? Well, it's simple, we should use a function expression rather than an arrow function:

spyOn(MyClass.prototype, "myMethod").and.fake(function(){
 this.items = mockData.items;
});

Other than its cool syntax Arrow functions trap the lexical this rather than using a dynamic this. This is very useful for event handlers, callbacks... and has made the typical "self-closure" pattern disappear, I mean:

self = this;
myButton.addEventListener("click", function(){
 self.myMethod();
});

//has given place to:
myButton.addEventListener("click", () => this.myMethod());

An arrow function binds to the function the this that exists at the moment of creating the function. The arrow function gets bound to that this similar to when you call function.prototype.bind. Once you have a bound function, calling bind on it again will not have a real effect. You get a new function wrapping the bound one, but the invokation will call the internal function with the first bound this. I guess function.prototype.bind creates a wrapper that uses function.prototype.call, and function.prototype.call is useless with bound functions:


class Person{
 constructor(name){
  this.name = name;
 }
 
 sayHi(){
  return "Hi, I'm " + this.name;
 }
}

let f1 = Person.prototype.sayHi.bind({name: "Francois"});
console.log(f1());

console.log(f1.call({name: "Chloe"}));

let f2 = f1.bind({name: "Chloe"});
console.log(f2());

//Hi, I'm Francois
//Hi, I'm Francois
//Hi, I'm Francois

I assume Jasmine is using using Function.prototype.bind to provide the this to the function invoked from callFake, so an arrow won't make it.

Notice that both functions created with Function.prototype.bind and arrow functions do not have a .prototype property (obviously they still have a [[Prototype]] property as every JavaScript object) and can not be used as a constructor with new (you'll get an "is not a constructor" error)

Sunday, 30 June 2019

CAP des Banlieus

J'en ai marré/I'm fed up:

  • I'm fed up of Racialists that consider Racialism the new antiracism.
  • I'm fed up of "Identitarians" that defend the identity of the country from which their ancestors fled escaping from poverty rather than defending the country where they've been born and grown, the country that has given them all the chances that they have decided to drop so they can live happy in their victimism.
  • I'm fed up of communitarists that try to close themselves in a community defined by religion, skin color or external countries, rather than the national community.
  • I'm fed up of so called "antifascists" that work hand in hand with IslamoFascists and xenophobic indigenists.
  • I'm fed up of religious foundamentalists trying to impose on us the shit laws of their medieval society.
  • I'm fed up of "Anticolonial activists" (Indigenists), that fight against the European colononialism of centuries ago (when a more advanced culture extended its control over less advanced societies) and defend the current colonialization of European soil by backward cultures...
  • I'm fed up of Houria Bouteldja and Medine (le "rappeur" islamiste), and demand them to be immediatelly remigrated into their beloved Algerian shitholes.

  • I'm fed up of the Rap anti-French, anti-white and islamo-supremacist.

  • I'm fed up of people that denounce the European slave trade but have nothing to say about the Arab slave trade (that was much worse in numbers and probably way more cruel).
  • I'm fed up of those who know nothing about Barbary corsairs seizing European women and children and turning them into sex slaves (hum, sounds like ISIS, maybe there's a certain religion as common basis in both cases...)
  • I'm fed up of Maghrebian and Turkish ultra-nationalists that with all their xenophobia and histerical nationalism make any European "facha" look like a love and flowers hippy.

  • I'm fed up of seeing people born and raised in France to leverage any opportunity to wave the flag of their parents country rather than the French flag.
  • I'm fed up of seeing those same people spit of the French flag and make monkey sounds when the Marseillaise resounds.
  • I'm fed up of seeing those same people using their "piece d'identité" (French ID card) to receive the social aids that allow them to spend their days complaining and conspiring against France, rather than working to keep it alive.
  • I'm fed up of retarded people that think that all cultures are equal.
  • I'm fed up of all those that think that asking immigrants to integrate and assimilate is fascism...
  • I'm fed up of the leftist scum that defends and promotes all the things I'm fed up with. Melenchon, Benoit Hamon... History will remind you as what you are: traitors, cowards, collabos and fascists (you try to impose on us a failed model of multicultural/multiconflictual society without asking for our approval).

And today, I'm particularly fed up with La Coupe d'Afrique des banlieus/African Cup of the "French" suburban neighbourhoods. So this month the African Footbal Cup is being played, and people of African descent born and raised in France decided to play an African Cup in their neighbourhoods. So they made teams based on the country of their parents/grandparents, put on the t-shirts of those countries, waved flags of those countries, sweared loyalty to those countries hitting their chests, sang the anthems of those countries, felt an irrational pride for those countries, shitholes (with all my respect) like Algeria, Mali, Senegal, Turkey (yeah, the Turks decided to join the party, even if they hate Africans with all their soul)... where most of them have rarely set foot... and so on and so on. All of this on French soil, perpetrated by people born and raised in France and taking advantage of the French System... The black guy that came up with the idea explains that he decided to make teams based on nationalities to avoid the conflicts that would have erupted if they had made the teams based on neighbourhoods... OK, it would make sense if all those people had a feeling of being French and their "parents nation" were just a third level identity, but that's not the case at all. The guy goes on to tell us that he does not need to justify how French he is, he is obviously French because he has a French ID (Francais de papiers), pays with euros and drives a French car... wow, I really can't refute that...

You don't need to understand French to understand this video. All you need to understand is that all those people wearing a foreign "uniform", waving a foreign flag and singing a foreign anthem are doing so in France, and were born and raised in France. You also need to understand the the leftist journalists in the video (save for 1 of them, obviously not a leftist) can not believe how absolutely cool the whole thing is. How a great example of the "Vivre ensemble"/Living together, they are making... Yes, living together among Africans, "a cote des Francais" (apart from the French).

Cerise sur le gateu (icing on the cake), there's something that I guess is not in accordance with the French Laicité principles...There's been a match between a Muslim team and Christian team! Wow, c'est vraiment trop cool, n'est-ce pas? et apres!? (it's too cool, right? what's next!?) Maybe a match between gays and heteros, or between gays and bisexuals or... wow, there are so many ideas flowing...

Friday, 28 June 2019

Promises vs Observables

Reactive Extensions (I've only used them in JavaScript/TypeScript with rxjs) is a really powerful tool and the more one plays with them more aware one becomes. Their aim is making easy to work with push streams (sequences) of data (I had given a classification of streams types here). It gives you so much power when compared to basic/classic event listeners.

On the other side, when working with an asynchronous operation that returns just once (it can return a single value or a collection, but it returns it just once) returning a Promise and using async/await moves you into a world miles ahead of the classic callback paradigm used for continuing asynchronous operations.

From the above, it would seem clear that we'll use Observables or Promises + async + await depending on whether we have multiple data or single data. But then, you find that the Angular HttpClient returns an Observable rather than a Promise and it seems odd. Even worse, if understanding how the magic of async/await and Promises (or Tasks in .Net) was not an easy endeavor for you, it hurts hard to read people saying that Promises are no longer cool and only Observables rule... what the fuck!?

There are many articles comparing Promises and Observables, this one is particularly good. You'll find also many discussions about why even when dealing only with a single value Observables are supposed to be always superior to Promises, and you'll find many disidents, like me :-). Observables can be cancelled and they are lazy, that's why even for a single data operation like an http request, they are supposed to be superior. That's true and that's false. Let me explain.

For those situations where you could need to cancel the http request, or you want to set it but run it lazily, yes, returning and Observable is a better option, but how often do you need any of those 2 features for a http request? Honestly, I hardly can think of a single case where I've needed that... On the other side, even after becoming familiar with pipe, flatmap, of... I think the cleanliness of the code that you can write with async-await lives in a different galaxy than the one you write with Observables. Let's see an example.

Let's say I have 2 async operations that I want to run sequentially, passing the result of the first one to the second one. Each operation would be like a http request, but in order to be able to run this code without depending on a server I'm just doing a sort of simulation.


function getUserId(userName:string, callback: (id:number) => void){
 let users: { [key: string]: number } = {
  anonymous: -1,
  francois: 1,
  chloe: 2
 };
 setTimeout(() => callback(users[userName] as number), 2000);
}

function getPermissions(id:number, callback: (permissions:string[]) => void){
 let permissions: { [key: number]: string[] } = {
  1: ["r", "w"],
  2: ["r"]
 };
 setTimeout(() => callback(permissions[id]), 2000);
}

Promises + async + await

I wrap each operation in a Promise returning function:

function promisifiedGetUserId(userName:string): Promise{
 return new Promise(res => getUserId(userName, res));
}

function promisifiedGetPermissions(id:number): Promise{
 return new Promise(res => getPermissions(id, res));
}

And now I can use them like this:

async function promisesTest(userName:string){
 let id = await promisifiedGetUserId(userName);
 console.log("id: " + id);

 let permissions: string[];
 if (id === -1){
  permissions = [];
 }
 else{
  permissions =  await promisifiedGetPermissions(id);
 }
 
 console.log("permissions: " + permissions.join(","));
} 

//sort of C#'s "async main"
(async () => {
 await promisesTest("francois");
 await promisesTest("anonymous");
})();

Observables

I wrap each operation in an Observable returning function:

function observableGetUserId(userName:string): Observable{
 return new Observable(observer => getUserId(userName, id => observer.next(id)));
}

function observableGetPermissions(id:number): Observable{
 return new Observable(observer => getPermissions(id, permissions => observer.next(permissions)));
}

And now I can use them like this:

function observablesTest(userName:string){
 observableGetUserId(userName).pipe(
  flatMap(id => {
   console.log("id: " + id);
   if (id === -1){
    return of([]);
   }
   else{
    return observableGetPermissions(id);
   }
  })
 ).subscribe(permissions => console.log("permissions: " + permissions.join(",")));
}

observablesTest("francois");
//observablesTest("anonymous");
 

I think the first code is way more clear and natural, don't you think? So Promises, await and async are alive and well! I've uploaded the code into a gist.

This said, I think the decision done by Angular of returning an Observable with their http client is OK. Converting that Observable to a Promise is as simple as invoking myObservable.toPromise(), so you can still do good use of async/await. At the same time, if you are in one of those cases where canceability and laziness are useful to use, that Observable is what you need, so in the end Angular is giving you the most versatile solution.

Sunday, 23 June 2019

Stockholm

STHLM is not a new web technology, it's the trendy, abbreviated term used by locals for referring to Stockholm. I've been lucky to spend a few days in this gorgeous city recently. My perception of beauty has evolved over years, as my interests and experiences have changed. Owing to that, to fading memories and to how the accumulation of surprises make new surprises harder to happen... it's not fair to do a permanent ranking of my most beautiful cities. Well, that for me Paris is the most beautiful city in the world is something permanent, universal and atemporal, that I can say for sure... but for other cities, placing them in an exact location in a ranking is very difficult. However, with my current taste for architecture, urbanism and societal factors, I can say that as of today, Stockholm is the second most beautiful city that I know (yes, I'm placing this Nordic treasure above Vienna, Prague, Budapest, Lisbon, Lyon, Tallinn, Berlin...)

The Geographic setting of Stockholm is top-notch. The central part of the city (I'm not talking just of downtown, but of what you see in the map above) is made up of 14 islands laid between Lake Mälaren and the Baltic sea. There's water everywhere! Islands mean bridges, and those bridges are pretty diverse. While some of those in the most central and old part give you an amazing Venice feeling, others joining islands that are slightly hilly are huge, elevated bridges (like Vasterbron), that kind of make you feel like spitting to see the hypnotic play of your saliva with gravity and reflect on how it will travel now into the sea, and that you can compare a bit to those in Porto. As I've said, some of the islands are hilly, so you have some amazing views, like those from Soder Malarstrand. This is northern Europe, so in spite of the crazy summers that they are getting in the last years (during my stay there in early June we reached 27 degrees!!!) the natural landscape is beautifully green.

Architecture. Everyone has heard about Nordic design, so it's easy to expect that their good taste for furniture and home decoration would extend also to the buildings themselves. On the other side, documentaries and texts about the Swedish welfare state and strong economy tend to mention that before the WWI Sweden was a very poor country. Yes, it was a poor country during that period, but before that Sweden had been an Scandinavian empire, so you can assume that you'll find amazing historical buildings. And yes, that's true. The old town, Gamla Stan, has beautiful medieval houses (think of those in Tallinn), gorgeous brick gothic churches, and massive baroque-renaissance buildings (like the Royal Palace). You'll find also some amazing medieval buildings in Soder. Then you have the elegant late XIX century buildings of Ostermalm. The architecture is different, but in a sense we could think of this area as if Baron Haussmann had cast his spell further north. You'll find similar elegant buildings scattered over Vasastan, along with many more simple but also pretty nice buildings of the early XX century. Height of the constructions is really harmonious, most of the central part of the city is made up of 5 to 7 stories buildings, with occasional taller buildings. There are some skyscrappers (for European standards, that is, more than 85 meters) and high-rise buildings, but not organized in clusters, but as independent constructions scattered over the cityscape conforming points of reference. I've said in previous posts that this is the approach that I like more when it comes the relation of a city with high-rise buildings, independent towers that make the modern reflection of the church towers of medieval cities (you had one here and there, one in each neighbourhood let's say, not a whole neighbourhood made up of church towers...).
As someone with a sort of fetish with train stations and large extension of rail tracks entering the city and lined with buildings, Stockholm did not disappoint me. I particularly liked the odd view of the Tunelbana (metro) that comes to light out of the slightly elevated Soder, crosses to Gamla Stan through a bridge and goes underground as it touches this island.

Calm city. I had read and watched a lot about the islamisation of Sweden and the associated criminality (and "youngsters" burning cars and throwing stones at the police and other cultural expressions of the "victims of society"...), so I was expecting something that for sure would not be that bad as France or Belgium, but would revolt me. That's not been the case at all. Obviously I had nothing to see/do in the infamous ghettos (Rinkeby...) and the thing is that most of the scum living in the bad areas (I'm talking about the islamists and criminals that live there, of course there are normal people that have the bad luck of having to live in those areas) does not seem to travel too much to the central area, meaning that the city felt really calm to me and I hardly saw any signs of islamic separatism (Niqaabs or similarly segregationist female clothing, beardy bastards with the islamic male dress code, halal shops everywhere...) Furthermore, I hardly saw any "youngster" with the typical "racaille" dress code. It made me realize that in this sense France/Belgium is fucked up to a much greater extent than the rest of Europe.

All our experiences are deeply subjective, so I came to wonder to what extent my fascination with this city was justified or it was just me, the moment and some particular "stars alignment". The other day, while taking a coffee with one friend (that has traveled way further than me) he agreed with me, telling me that STHLM was one of the 3 more beautiful cities he had set foot on.

I'll close this post with some unordered pics:

Saturday, 1 June 2019

Extract - Remove Properties

Recent versions of JavaScript have made it terribly easy to add or overwrite properties of one object with those of another object, by means of Object.prototype.assign (which is also great for shallow cloning). But, what if we want to go in the other sense, create a new object by extracting certain properties from another object? Well, modern JavaScript makes this amazingly concise, let's see:

let source = {a:1, b:2, c:3, d:4};

//picking some values from an object
//notice the extra "()" to prevent it from being considered a block
let picked1 = (({a,b})=>({a, b}))(source);

console.log(picked1);
//{ a: 1, b: 2 }

So, what am I doing there? We declare an arrow function and immediately invoke it. This function uses destructured assignment for its parameters, so it will get the a and b properties of the source object that we are passing over assigned to a and b local variables. Then we put those 2 variables in a new object and return it. Sweet!

There are some additions that we can mix in, like using some default value in case the souce object lacks some of the properties:

//picking and using some default values
source = {a:1};
let picked2 = (({ a="x", c="y" }) => ({ a, c }))();

console.log(picked2);
//{ a: 1, c: 'y' }

And what if the source object is null?

//what if I don't pass anything:
source = null;
try{
 picked = (({ a="x", c="y" }) => ({ a, c }))(source); //it crashes
 console.log(picked);
}
catch(ex){
 console.log("Error");
 //Error: Cannot destructure property `a` of 'undefined' or 'null'.
}

We get an error, as we can not destructure from and undefined/null object. We can control this problem like this:

//in order to control that case where we pass no parameter, we add the extra "= {}" thing
let picked3 = (({ a="x", c="y" } = {}) => ({ a, c }))(); 
console.log(picked3);
//{ a: 'x', c: 'y' }  

We are using an empty object, {}, as parameter to the destructuring operation in case no object is provided (and we use default values for the missing properties). I had already use this technique in this post but at that time I just saw it as magic.

Finally, what if rather than extracting values into a new object we just want to remove them? No magic syntax that I'm aware of, but we can use some rather concise code like this:

function removeProperties(source, propsToRemove){
 return propsToRemove.reduce((res, prop) => {
  delete res[prop];
  return res;
 }, source);
}

let obj = {a:1, b:2, c:3, d:4, e:5, f:6};
let res = removeProperties(obj, ["c", "d"]);
console.log(res);
//{ a: 1, b: 2, e: 5, f: 6 }

Saturday, 25 May 2019

Huawei Campus

Innovation and imitation, those two forces shape our present and our future. There's a general tendency to disdain imitation, but I fiercely dissent. If something is good, imitating it is a smart decision. As long as the original is good and the copy is good, imitation is a pretty good approach, much better than creating something new but worse. I think we all have heard of some examples of imitating/replicating some iconic architecture landmarks, even imitation of certain neighbourhoods. A small "Tour Eiffel", a neighbourhood inspired by Venice canals... things like that.

As usual, modern China has taken this to the next level. Already in 2007 they opened a neighbourhood in one more of those multi-million inhabitants cities of odd name, that tries to be a replica of Paris. It seems like it has not been particularly successful, but well, if sadly the islamic invasion of Europe continues at the current rate, maybe in 20 years anyone that wants to enjoy the marvels of Hausmannian Parisian Architecture without being surrounded by stinky "barbus", burkas and drug dealers will have have no other choice but flying to China... It seems they have built similar neighbourhoods imitating London and other famous cities.

If that seems cool/crazy, what Huawei has done with their new campus in Dongguan is just mesmerizing:

12 separate "towns." Each section is modeled after a different major European city, and each city can hold around 2,000 people.

Some of the cities used for inspiration for the campus include Paris; Verona, Italy; Granada, Spain; and Bruges, Belgium.

It's absolutely amazing, and what shocked me the most is the German Castle dominating the artificial lake. Wow, that's beautiful!!!

Sunday, 19 May 2019

C#, JSON, dynamic...

I've been doing some json stuff in .Net (Json.Net) lately slightly beyond serializing and deserializing. It's basic stuff anyway, but it'll be useful (to me) to dump it here.

First, the basic distinction between the two main classes that we use when dealing with Json in .Net, JsonConvert and JObject. When we already have a .Net class that matches with the json string, we use JsonConvert.DeserializeObject<MyType>. If that's not the case, we use JObject.Parse to deserialize into a JObject, that with the power of dynamic provides us a very convenient way to read and manipulate that json structure. The only source of confusion is that JsonConvert.DeserializeObject<Object>(item), JsonConvert.DeserializeObject<dynamic>(item) and JsonConvert.DeserializeObject(item) will return a JObject, so it's equivalent to doing a JObject.Parse().

The casing difference between camelCase json and PascalCase properties in C# objects continues to make things a bit messy. Out of the box, when deserializing with JsonConvert.DeserializeObject Json.Net will nicely try to find in our .Net class a public property that matches either camel (Person.name) or Pascal (Person.Name) with the json camelCase property ("{'name':'Iyan'}"). So we don't need the horror of changing the standar naming convention.

class PersonCamel
{
 public string name {get;set;}
 public int age {get;set;}
 public override string ToString()
 {
  return this.name + " - " + this.age;
 }
}

class Person
{
 public string Name {get;set;}
 public int Age {get;set;}
 public override string ToString()
 {
  return this.Name + " - " + this.Age;
 }
}

var jsonPerson = @"{
 'name':'Eric',
 'age': 49
}";

personCamel = JsonConvert.DeserializeObject<PersonCamel>(jsonPerson);
Console.WriteLine(personCamel.ToString());
//xuan - 45

person = JsonConvert.DeserializeObject<Person>(jsonPerson);
Console.WriteLine(person.ToString());
//xuan - 45

When serializing our C# class to json, by default JsonConvert will use the name property as it is in our class. So if we want to avoid the pain of ending up with json strings in PascalCase, we'll have to help the serializer a bit with one of these 2 techniques:

JsonConvert.SerializeObject(person, new JsonSerializerSettings
{
 ContractResolver = new DefaultContractResolver
 {
  NamingStrategy = new CamelCaseNamingStrategy()
 }
});


JsonConvert.SerializeObject(person, new JsonSerializerSettings 
{ 
 ContractResolver = new CamelCasePropertyNamesContractResolver() 
});

Let's move now to more interesting stuff with JObject, dynamic and explicit/implicit conversions (I had already talked about this in this post). Let's see some code:

var jsonResult = @"{
'result':'OK',
'users': [
 {
 'name':'xuan',
 'age': 45
 }, 
 {
 'name':'Francois',
 'age': 47
 }
  ]
}";

var jsonPerson = @"{
 'name':'Eric',
 'age': 49
}";

void TestJObjQuerying(string jsonResult, string jsonPerson)
{
 Console.WriteLine("TestJObjQuerying");
 
 dynamic resultJObj = JsonConvert.DeserializeObject(jsonResult);
 //to be able to use a linq query on the array we need to cast as JArray
 //then, as JArray implements IEnumerable of JToken we need to cast to dynamic again
 Console.WriteLine(String.Join(",", ((JArray)(resultJObj.users)).Select(it => (((dynamic)it).name))));
 
 
 
 dynamic personJObj = JObject.Parse(jsonPerson);
 
 var name1 = personJObj.name;
 Console.WriteLine(name1.GetType().Name);//JValue
 
 string name2 = personJObj.name; //implicit conversion
 Console.WriteLine(name2.GetType().Name); //string
 
 var name3 = (string)(personJObj.name); //explicit conversion
 Console.WriteLine(name3.GetType().Name);//string
 
 Func myFunc = jObj => jObj.name; //implicit conversion for the return typle
 var name4 = myFunc(personJObj);
 Console.WriteLine(name4.GetType().Name);//string
 
}

TestJObjQuerying(jsonResult, jsonPerson);

We know that resultJObj.users is a JArray, but we need to hint the compiler with a cast, otherwise the compiler will consider it just as dynamic (the field of a dynamic object is a dynamic). JArray provides the Select method not as an own method, but as an Extension method available because it implements IEnumerable. Extension methods and dynamic do not play well together, so we need that casting for the compiler to set the call to Linq.Enumerable.Select. That Select returns an IEnumerable so in order for the access to the name property to work we need to do a casting to dynamic.

The next lines in the method are a reminder of how implicit and explicit conversions make JObjects and dynamic work like magic.

A long while ago I already posted about a very interesting possibility, deserialize an object into a JObject and then take one part of that structure for which we have a .Net Type and convert it to that type by means of ToObject. In my old sample I was passing a serializer to ToObject because of the camel to Pascal, but now, same as I've just explained for JsonConvert, this is managed automatically.

 dynamic obj = JObject.Parse(jsonResult);
 personJObject = obj.users[0];
 var person = personJObject.ToObject<Person>(); //camel to Pascal works good automatically 

The inverse procedure can also be useful. We have a .Net class and we want to serialize it to json with some additional fields. We'll use FromObject like this:

var person = new Person{
 Name = "Jean",
 Age = 52
};
dynamic jPerson = JObject.FromObject(person);
jPerson.City = "Marseille";
Console.WriteLine(jPerson.ToString());
 
//{
//  "Name": "Jean",
//  "Age": 52,
//  "City": "Marseille"
//}

The problem with the above is that there's not an out of the box way to serialize the JObject to camelCase json. You'll have to use some more elaborate technique as the one described here.