Thursday 26 July 2012

JavaScript arguments

I've come across lately with another amazing JavaScript feature, and it's not a ECMAScript 5 novelty or ES6 proposal, it's something that exists in the language since its inception, the arguments array-like object.

OK, sure you (as me) have used it previously, so what's the fuzz with it? well, the thing is that I used to think of arguments as an array of references to the objects referenced by the local variables. That means that it's good for read access, but if I wanted to assign a new value to let's say arguments[0], arguments would point to that new object, but the corresponding variable would still point to the initial object... Well, that's not the case, we should better think of arguments as a (sort of) Array of references to references to objects (think in C#'s ref keyword). This means that if we make a local variable point to a different object, its corresponding arguments[i] will correctly point to that object, and vice versa.

Let's see an example:

function parseTexts(txt, person){
 txt += " modified";
 console.log(arguments[0]);
 console.log(txt);
 
 arguments[0] = arguments[0] + " modified2";
 console.log(arguments[0]);
 console.log(txt);
 
 //quite astonishing, even passing the arguments pseudo array to another function the changes "replciate"
 (function(args){
  args[0] += " modified3";
  args[1] = {name: "xuan 2"};
 }(arguments));
  arguments[0] = arguments[0] + " modified2";
 console.log(arguments[0]);
 console.log(txt);
 console.log(arguments[1].name);
 console.log(person.name);
}

If you run the code above you'll see that arguments[0] and txt continue to point to the same object, regardless of which one you used for the reassignation.

I suddenly realized this could be pretty useful to fix a minor annoyance I'm faced with quite often. As you know, JavaScript lacks default parameters, so we end up writing code like this:

function Person(name, lastname){
name = name || "John";
lastname = lastname || "Doe";
}

Well, if we're dealing with a long number of arguments that becomes boilerplate, so, let's use arguments, as we've seen that if we change where it points to, we'll be in fact changing where the local variable points to:

function setDefaults(defaults, params){
 defaults.forEach(function(it, i){
  if (params[i] === undefined)
   params[i] = it; 
 });
}

function Person2(name, age, city){
 setDefaults(["xuan", 3, "Xixón"], arguments);
 
}

A common alternative to the solution above is using the $.extend - options object combination commonly used in jQuery plugins:

function Person2(options){
options = $.extend({
name: "xuan",
age: 3,
city: "Xixón"
}, options);

}
Person2({name: "xuan"})

The obvious drawback here is that instead of working directly with the parameters you'll have to use properties in a single local variable.

Update, 2013/02/07:
Unfortunately it seems like the beautiful arguments pseudo array will be getting less and less love in the near future. First, if working on strict mode, it will no longer be "live bound" to the variables, so that all the magic that I described above will be gone, if you modify the variable, the bucket in the arguments pseudo array will continue to point to the old value, and vice versa. You can read more in the "Making eval and arguments simpler" section here
Furthermore, as explained here it seems like there are plans to add new simplified constructs to the language that will end up replacing arguments

Thursday 19 July 2012

ECMAScript 5 Properties (and interception)

In the last week I've been exploring the additions to Properties that ECMAScript 5 provides. There are tons of articles around about this, like this one by John Resign, and this time I don't feel like copy pasting here what others properly explain. The MDN documentation about defineProperty, getOwnPropertyDescriptor and so on is an essential reference.

One basic idea that I'd like to highlight is that as JavaScript objects behave like dictionaries we tend to think of them as pairs formed by a string key and a reference to the value. Well, even in EcmaScript 3, this is not that simple. We don't have a reference to the value, but a reference to an object that in turn contains a reference to that value and some additional fields acting as metadata [[enumerable]]... EcmaScript 5 gives us (read/write) access to those metadata, and adds getters/setters to the mix (bear in mind that we can have 2 types of properties: data properties (have a value), and accesor properties (have a getter-setter pair of functions)

When reading the defineProperty documentation and realizing that we can redefine an already existing property, a useful and obvious application occurred to me, property interception. We could redefine an already existing property (either a data or an accessor one) replacing it with an accessor property that should somehow have access to the old property. The most interesting of this is that this can be applied to the object itself, not needing the creation of a new proxy object as we do in Java or .Net with dynamic proxies(or with the proxies proposed for ECMAScript 6).

The implementation below defines closures for the getters and setters, trapping the old property descriptor if it already was an accessor property, or the store for the value if it was a data property.

//@obj: object being intercepted
//@key: string name of the property being intercepted
//@beforeGet, afterGet; functions with this signature: function(key, safeDesc)
//@beforeSet, afterSet; functions with this signature: function(key, newValue, safeDesc)
//these 4 interception functions expect to be launched with "this" pointing to the object's this
//warning, you can't do a this[key] inside those functions, we would get a stack overflow...
//that's the reason why we're passing that safeDesc object
//the beforeGet function could want to modify the returned value, if it returns something, we just return it and skip the normal get and afterGet
//the beforeSet function could want to prevent the set action, if it returns true, it means it want to prevent the assignation
//We're providing the afterGet functionality though indeed I can't think of any useful application for it
function interceptProperty(obj, key, beforeGet, afterGet, beforeSet, afterSet){
 var emptyFunc = function(){};
 beforeGet = beforeGet || emptyFunc;
 afterGet = afterGet || emptyFunc;
 beforeSet = beforeSet || emptyFunc;
 afterSet = afterSet || emptyFunc;
 //skip functions from interception
 if (obj[key] === undefined || typeof obj[key] == "function"){
  return;
 }
 
 var desc = Object.getOwnPropertyDescriptor(obj, key);
 
 if (desc.get || desc.set){
  console.log("intercepting accessor property: " + key);
  Object.defineProperty(obj, key, {
   get : desc.get ? function(){ 
    //if the beforeGet function returns something, it's that value what we want to return
    //well, in fact we could apply that logic of changing the value to return in the afterGet function better than in the beforeGet
    var result = beforeGet.call(this, key, desc);
    result = result || desc.get.call(this);
    afterGet.call(this, key, desc);
    return result;
   }: undefined,  
   set : desc.set ? function(newValue){ 
    //if the beforeSet function returns something, use it instead of newValue
    newValue = beforeSet.call(this, key, newValue, desc) || newValue;
    desc.set.call(this, newValue);
    afterSet.call(this, key, newValue, desc);
   }: undefined,
     enumerable : true,  
     configurable : true
  });
 }
 else{
  console.log("intercepting data property: " + key);
  var _value = obj[key];
  desc = {
   get : function(){
    return _value;
   },
   set : function(newValue){
    _value = newValue;
   }
  };
  Object.defineProperty(obj, key, {
   get : function(){ 
    _value = beforeGet.call(this, key, desc) || _value;
    afterGet.call(this, key, desc);
    return _value;
   },  
   set : function(newValue){ 
    _value = beforeSet.call(this, key, newValue, desc) || newValue;
    afterSet.call(this, key, newValue, desc);
   },
     enumerable : true,  
     configurable : true
  });
 }
}

You'll use it this way (we're intercepting the property setting, so that we can modify some of the values that are going to be set:

 var _beforeSet = function _beforeSet(key, newValue, safeDesc){
  if(newValue == "julian"){
   console.log("rewriting value to assign");
   return "iyán";
  } 
 };
 interceptProperty(p1, "name", null, null, _beforeSet);

So we have 4 interceptor functions: beforeGet, afterGet, beforeSet and afterSet. I can't think of any useful application of afterGet, but well, I prefer to provide the option just in case. beforeGet and afterGet will be called with the object where the property is being accessed as "this", and 2 parameters, a string representing the key, and a descriptor like object, with a get and set method that give us access to the value stored in the property, bypassing the get-set (this is essential, as if we were doing this[key] we would get a stack overflow (the beforeGet would call the getter and the getter the beforeGet and so on). beforeSet and afterSet add one more parameter, the new value being set. Returning a value from beforeGet or beforeSet tell our getter or setter that we want to change its behaviour, either return that returned value instead of the stored value, or setting that value rather than the new value provided to the setter.

You can grab the code here and here

Update The version above, with the beforeGet-afterGet, beforeSet-afterSet function pairs, resulted in a rather unnatural usage pattern. I've rewritten it to use a single getInterceptor, setInterceptor function. The code is now in github, and also provides method interception

A very important point to notice with Properties is that contrary to most of the JavaScript 5 additions (Function.bind, Array.forEach...) there's no way to simulate them for older engines (the code in this es5 shim makes a nice read), so you'll have to think it twice before adding them to your code.

Another important point to note is that we can't add custom attributes to properties, we can only just the defined ones (value, get, set, writable, enumerable, configurable). So forget about adding a "description" attribute or similar, you won't get an error, but it won't be added. Furthermore, each time we invoke getOwnPropertyDescriptor, it returns a new object representing the descriptor, not the descriptor itself stored in the Object. I guess the reason for that is that a property descriptor is not stored as a normal object, but as some sort of optimized structure, so when asked for it, ECMAScript has to map it to a conventional object. This means that this expression is false:
Object.getOwnPropertyDescriptor(o, "sayBye") == Object.getOwnPropertyDescriptor(o, "sayBye");

It's quite a pity, cause I had started to envision how elegant it could be to use custom property attributes to simulate advanced Object Oriented enums. That would have been a revision of what I wrote some months ago.

Tuesday 17 July 2012

Bratislava

Bratislava is like a little jewel to me, but it remains quite unknown for many travellers. Many people doing the popular Prague, Vienna, Budapest circuit skip the Slovak capital, and sure it's an important miss. I've already been there 3 times, and I continue to consider it worth a visit. If you're lucky to be in Vienna for a few days, you should leverage one of them with a day visit to Bratislava. It's pretty simple, you just go to what is left of Südbahnhof (the original station was demolished in December 2009, a few months after I was there for first time, to give place to the new Hauptbahnhof currently under construction), spend 14 euros in a return ticket to Bratislava (you can do the back trip on a different day and it gives you free travel in Bratislava's public transport) and do the 70 minutes trip to the old Hungarian capital (it served this role during the 150 years when Budapest was under Ottoman rule).

When leaving Vienna you'll have a nice view of the city's modern skyline from the bridge crossing the Danube

Then you'll see a flat landscape (as an Asturian it still shocks me to see how flat a good part of Europe is) with many fields used for Bio crops, some panelaks when approaching Bratislava, and finally you'll find yourself in in a rather ugly train station that gives a quite messy impression. I think that's quite OK, cause mess is one of the things that first come to my mind when I think about Bratislava, but it's a beautiful mess. When heading from the station to downtown you'll probably use an overpass from which you can see to the left an untidy mix of worn out early XX's buildings, socialist government-university buildings, the Slovak Radio Building and some glass and steel sky scrappers. Indeed, for a city of its size Bratislava has a rather surprising number of sky scrappers and though none of them is to remarkable neither by height or beauty, they certainly add to the charm of the city.

If you stroll down Stefanikova you'll see on your left a nice park (further to the left there's another park that I consider more interesting for its open space and its "Soviet feeling", I don't know how to explain it, but if there you'll probably understand me).

To the right you have an area with some nice old buildings quite in disrepair

Cross the pedestrian subway and you'll have Obchodna to your left. This is a lively shopping street, with some low rise colorful, freshly restored buildings, some grey ones with peeling facades, a Vietnamese market and a cheap and good enough Vegetarian (Hare Krishna) restaurant: Govinda.

To the right you see a nice, mainly pedestrian (I think only trams and buses drive along it) street, with 2 small churches to the right and that will take you to the Castle. The view of this slightly uphill street is one of my favourite views there.

Now you're in downtown. I won't expand too much on this, just check some properly written guide (wikitravel can be a good start), but I'll say that it's a pretty charming city centre. The main square is lovely, with a restored, art nouveau building that pretty much stands out. I should also highlight a small area close to the Cathedral with pedestrian almost medieval streets flanked by very old buildings. Now you should go the de Danube and stroll along the promenade. There you'll see a construction that is a real winner in my list of ugliest buildings in Europe, the Slovak National Gallery. Let me explain, the gallery consists of 2 parts, a beautiful old building, and a modern extension done in the 70's that looks like an authentic monstrosity to me. The pics in the wikipedia entry make it quite clear.
Go on along the Danube and get to the Nový Most (new bridge), now cross it and enjoy the view of that broad water extension flowing before your eyes (you can also check the concert posters put up along the pedestrian walk, thanks to that I've discovered Ambassador 21, the Belarusian incarnation of Atari Teeenage Riot).

You're in Petržalka now, the massive Panelák neighbourhood. Most tourists won't give a damn about this kind of tower block extensions, but I love cities and I love history, and these areas show us how European cities developed after WWII. In fact, I find these restored and coloured paneláks quite beautiful. You also have some more recent glass and steel buildings in the area, like the ones in Digital Park, hosting several IT companies. By the way, the huge presence of IT companies in Bratislava is amazing (Dell, Lenovo, Accenture...) though I guess it's mainly a "call center and support" thing, with quite little software development happening there.
Now you can stroll along a nice park by the river to get to the Stary Most (Old Bridge). This is an interesting concrete, steel and wood construction.

You cross over it to be back in "Bratislava proper". A bit to your left you'll see an area still in development with new office buildings. One of them caught my eye cause it's like a small version of London's City Hall.
And now, you must head to the last must see in this tour, the Blue Church.

The Blue Church is a really beautiful work by the amazingÖdön Lechner known as "the Hungarian Gaudi". I'd already visited this church in 2009, and at that time it didn't impress me that much, but in these last years I've developed a real taste for Art Nouveau/JugendStil/Secession... and this time I was delighted by this little gem. There are some crazy decorative items on the roofs, and the funniest thing of all is that there are some motifs on the walls that resemble inverted crosses :-)

In front of the church there's a very beautiful building following very similar lines and recently painted in pastel colors. The building's low railings are absolutely cute, green, organic, iconic Art Nouveau style. I've just found now that (it should not be much of a surprise) that such nice construction is also a work by Ödön Lechner

As bottom line I'll say that Bratislava probably can't show off any too unique feature, but it boasts a beautiful eclectic mix easily enjoyed on foot. I think the city's motto "Little big city" is sharply appropriate

Ah, of course, you can find some interesting street art there too



Saturday 14 July 2012

The Divide

This has been a very welcome surprise. I hadn't heard a word about this film and I just got to it after checking the list of films starred by Lauren German that sweety playing the main role in Hostel 2. So far this is the best film I've watched this year (excluding Incendies, but that piece of art plays on a different league

Dark, apocalyptic film where we're provided with almost zero background information. All we know is that some kind of Nuclear Attack has taken place drawing a group of men and women to find shelter in the sort of nuclear bunker built by their paranoid landlord. The group ends up trapped there, and all sort of conflicts arise. The first and obvious issue is the access and rationing of food and water, then we have issues with sex and power (well, aren't they the same? :-) The films grows harsher as it moves on, doing an excellent depiction of how human beings can degrade, both physically (radiation, lack of proper feeding...) and very especially at the moral level (some brainless tough guys turn into soulless degenerate beasts, one loving mother becomes their bitch seeking their protection...). The story gets more intense and claustrophobic by the minute and you end up with a French extreme cinema taste in your mouth. Well, after these 120 minutes of darkness and despair concluded I read that the director did previously direct one of the best exponents of that new wave of brutality, Frontiers.

So, just go and watch it, sure you can't find many better things to spend your time with

Friday 13 July 2012

Not just a matter of style

One could think that using a traditional for loop to iterate an array vs using the (relatively) new forEach method is just a matter of style, but I just realized today how handy the second approach comes for a rather particular case.

In this old post where I pondered about the usage of closures inside loops in C# and JavaScript, we could see how convoluted properly doing it in JavaScript could be, having to define an extra function. However, using the forEach method, as we already need a function for the iteration body, it seems pretty much more natural, just look the code below:


var buttons = [
 {text: "Open"},
 {text: "Save"},
 {text: "Exit"}
];

//------------------------------------------------
//this is the wrong way to do it, all closures trap the same "i" variable, so in the end, the value is 3 for all of them
for (var i=0; i<buttons.length; i++){
 buttons[i].click = function(){
  console.log(this.text + " is button " + i);
 };
}
buttons[0].click(); //prints 3
buttons[1].click(); //prints 3

//------------------------------------------------
//this options was fine, but the code is not too clean
for (var i=0; i<buttons.length; i++){
 buttons[i].click = (function(){
  var j = i;
  return function(){
   console.log(this.text + " is button " + j);
  }
 }());
}
buttons[0].click();  //prints 0
buttons[1].click();  //prints 1

//------------------------------------------------
//I bet this is much cleaner than the above
buttons.forEach(function(button, index){
 button.click = function(){
  console.log(this.text + " is button " + index);
 };
});
buttons[0].click(); //prints 0
buttons[1].click(); //prints 1

Sunday 8 July 2012

Underworld settings in Budapest

I'm a big fan of the whole Underworld saga in general, and of its first installment in particular. As I've already posted in several occasions, I pretty much like Vampire films, especially when they are depicted as elegant, aristocratic, modern types whose money allows them to play with high tech stuff (this is also present in films like Blade and Rise). If you add Kate Beckinsale dressed in a gothic latex outfit to the mix, you're turning my fantasies into reality...

I love almost every second of the first Underworld film, but the opening scene, with Selene under the rain, sat on that balcony overlooking that dark, timeless city, is one of my favorites. When I first was in Budapest, in 2009, I had already read that the film was filmed there, and watched the film once again to open my apetite for the city. It's something I usually do before travelling to a city, watching films set there, along of course with reading as much as I can about the history and the social situation of the place. However, once there I didn't try to identify locations of the film, and back at home, thought the city had a huge impact on me (the night views from the castle, the impressive early 20 century buildings with those dark facades in different grades of disrepair, my astonishment when contemplating the width the Danube reachs there...) I didn't think about the connection between the city and the film anymore.

When preparing my last trip the the Hungarian capital this June, I decided to watch Underworld again, and once more the opening scene deeply delighted me. I couldn't identify those impressive buildings, but I thought it would be Andrássy Ut (mainly cause it has the highest concentration of late XIX's early XX's buildings I knew of, and cause there are several metro stations along the avenue). I did some fast googling trying to find more, but I got mainly nothing.

Once in Budapest last month, I had to discard Andrássy Ut as the setting for that opening scene, as there's not a small square like the one in the film, and no building seemed to match with the ones from which Selene watches the city. Finding this setting was not too high in my priority list, so just forgot about it while enjoying my roaming around the wide avenues lined by magnificent, worn out buildings (it's the perfect counterpart to Vienna or Prague). To my surprise, I suddenly stumbled upon the place:

check it out on google maps

On the Pest side of the Erzsébet bridge 2 imposing buildings rise majestically, one to each side of Szabad satjó, and if you stroll a few meters, you find the small square with a small church and a fountain with a mask (though there's no water flowing there now). Right there you have the Metro station where Michael enters (but not where the shooting takes place). That subway entrance appears on the film, but the interior of the station does not match, the one in the film is larger and the walls are different.

Back in Asturies I did some more research, finding this interesting page stating this:

The opening battle between the Lycans and Vampires takes place on the Budapest Metro and although it is difficult to work out which station this is set at, it does look a lot like Arpad Hid station on the M3 line. Interestingly the New York subway entrances are actually based on those in Budapest.

You can confirm that I'm not cheating you by comparing my pics with the screenshots from the film:

Buildings

Square

By the way, last week I watched another quite good film set in Budapest, 8mm II. This erotically charged thriller also revolves around night creatures, but human ones instead of Vampires and Lycans. The main character lives in a flat just across St. Stephen's Basilica, and one of the characters is the Hungarian beauty that appears for a few minutes in Underworld I and II in the role of Amelia

Tuesday 3 July 2012

Animated Accordion

Wow, I was on vacation wandering around Central Europe (I intend to write some entries about this) for nearly 2 weeks, and then I was tired-busy enough that all in all I've been 20 days without posting... well, I doubt anyone has missed the activity in this blog... but anyway, time for a fast entry.

Probably many people will find this effect irritating, but since my times with Action Script almost one decade ago I've ever found all this sort of animations fascinating. So, while jQuery UI Accordion makes a nice job, I feel like in some cases (like when it's used as the central piece of some "presentation like" page), it needs something to make it "cooler". Displaying the different headers of the accordion in a gradual manner seems like a neat effect to me, and it's been pretty simple to implement

I've used it here for this landing page (by the way, my uncle has published a new book, it's a shame that it's in Spanish, cause it's well worth a read and will be freely available in a few weeks):

Jesus Aller

and this is the code:

var accordionStartAnimation = function _accordionStartAnimation(duration, delay){
 this.duration = duration || 500;
 this.delay = delay || 200;
};

accordionStartAnimation.prototype.animate = function _animate($accordion){
 this.$accordion = $accordion;
 this.$headers = this.$accordion.find("> h3").hide();
 this.$contents = this.$headers.next("div").hide();
 this.curItem = 0;
 this._animateNext();
};

accordionStartAnimation.prototype._animateNext = function _animateNext(){
 var self = this; 
 if (this.curItem < this.$headers.length){
  this.$headers.eq(this.curItem).show(this.duration, function(){
   setTimeout(function(){
    self._animateNext();
   }, self.delay);
  });
  this.curItem++;
 }
 else{
  setTimeout(function(){
   self.$contents.eq(0).show(self.duration);
  }, this.delay);
 } 
};



$booksAccordion = $("#booksAccordion").accordion({
  autoHeight: false,
  fillSpace: true
   });
 new accordionStartAnimation().animate($booksAccordion);

As you can see the idea is pretty simple, we create a normal accordion, and immediately hide all its elements (headers and contents). Then we chain the animated display of each of these headers (adding a minor delay between animations) and when the last header is done we show the content of the first item