Earlier today, a friend of mine wanted me to teach him how to do JavaScript sockets. Okay, I happily obliged. But honestly:

  • I have only used Sockets once
  • I have only built a Node socket server once, and never in another language
  • Mainly I just learned sockets via Node.js videos, especially the early intro videos.

Anyways, the concept was clear, and everyone had grasp of what a public chatserver would consist. As for the code… Let’s just say I had a cheat sheet. But anyways, the session boiled down not of sockets nor the JavaScript that ran it, but instead, I was explaining more of how JavaScript ran in those lines of spaghetti.

The point is, no matter how complex your code is, your JavaScript will boil down into 2 basic paths of execution: Synchronous and Asynchronous. The former is synonymous to the concept of procedural code, whereas the latter is more akin to threading or parallel-ing. To put into simple terms, JavaScript is just a set of do’s and todo’s respectively. You either tell it what to do now, or tell it to do something ASAP.

Procedural code or “do’s” is pretty much structured like commands. It’s like telling JS “Do this, I give you this, do that, NOW!!!”. Think of it like an arsonist, and we tell him to do what he is advertised to do:

//Very harsh, isn't it?
var arsonist = new Arsonist('Frank');
arsonist.burnHouse();
arsonist.detonateMine();
arsonist.incinerateCorpse();

As for the async aspect or the “todo’s”, imagine that we are not around to tell JS what to do when things happen. The best part of async JS is that you don’t know when it happens, like AJAX for instance. You don’t know when the server responds, nor if it will respond to you at all. But instead of waiting for something that might not even happen, we give JS a very detailed “todo list” of what to do when they do happen.

So just in case someone stole our arsonist friend when we are not around and tells him what to do, imagine we set-up a fireman beforehand, and told him what to do when things happen:

//Suppose we had a fireman
var fireman = new Fireman('Pete');

//For each event, provide a "todo", which is basically a function
fireman.on('fire',function(event){
  console.log('I shall put out fire');
});

fireman.on('catStuckOnTree',function(event){
  console.log('I shall bring ladder');
});

fireman.on('seePrettyGirl',function(event){
  console.log('Get beaten by an astronaut');
});

As an aside: Another nice thing of JS is that if programmed verbosely, it does sound like you are reading sentences instead of code. So if you omit the technical and syntactical parts, you’d be reading the bindings as “Fireman: on fire, I shall put out fire” and so on.

So there you have it. That’s another simple explanation for another complex definition in JS.

So I have a Linux setup, Lubuntu 12.10 to be exact. Who said I can’t play Windows games? There’s Wine which pretty much runs “everything”. But it isn’t installed by default, so open up a terminal and enter the following to install Wine:

sudo apt-get install wine

So that’s it? Can I play now?

No, not yet. It’s not yet everything. You need a few DLLs that are required by your games. There’s an article that discusses the requirements to run games on Wine. The part we are interested in is the installation of those DLLs. The problem was, the author didn’t bother sticking in a script or at least a one-liner to install them in one fell swoop.

So for the same of convenience, I made this one-liner that will install some essentials to run games:

winetricks d3dx10 d3dx11_42 d3dx11_43 d3dx9 d3dx9_26 d3dx9_28 d3dx9_31 d3dx9_35 d3dx9_36 d3dx9_39 d3dx9_42 d3dx9_43 d3dxof vcrun2005 vcrun2008 vcrun2010 wininet xact xact_jun2010 xinput quartz vcrun6 vcrun6sp6 ogg allcodecs

The DLLs are taken as of this writing. There may be additional DLLs from updates, especially in the d3dx* department. Once downloaded, these installers are cached. In the event that you corrupted your prefix (the place where everything Windows is placed), and need to delete the it, reinstalling these packages is just a matter of using the cached installers to install them again.

I also don’t know any method to install stuff in Winetricks using wildcards, like winetricks d3dx* to install all packages starting with d3dx. Maybe there’s a built-in way to install it which I don’t know yet or maybe some “grep tricks”.

Anyways, after all that’s done, go to your game installer directory/disc and run the setup using wine

wine [setupfile]

After that, you are good to go! You might want to check the Wine AppDB for compatibility though. Some games need a bit of wrestling to get them to work.

As far as I know, the following games work on my set-up:

  • Command & Conquer: Generals and Zero Hour
  • WarCraft III: RoC & FT
  • Starcraft 1 and Broodwar
  • Counter-Strike 1.6
  • Sniper Elite 1

For months of using Lubuntu, I have always wanted to remove those Penguin games. Ok, I don’t really hate them, but they just look well… stupid :D (No offense, but they are). Unfortunately, all efforts were in vain.

I finally stumbled across some articles. To my surprise, the games are not packaged individually. They are packaged as ace-of-penguins. Hooraay! Pinned you at last!

Without hesitation, I removed them. Happy me!

Over at Code Review, we usually prefer native implementations of routines for performance reasons. But we sometimes have exceptions, especially when the native implementation is slower, get’s too messy to read, or if we see a potential maintainability issue.

Among these comparisons is jQuery.each() and normal for/for-in loops for iteration purposes. This also goes for other libraries’ .each() implementations and not just jQuery’s. But in this article, we’ll discuss about jQuery’s implementation since it’s the most widely used.

Of course, the native loops win hands down in performance. jQuery.each() itself is just an abstraction of these native loops, with additional checks and routines, making it slower. However, here are a few cases where using jQuery.each() might make more sense than native loops.

Block scope binding

This comes up at StackOverflow very often, like once in a week or two. To demonstrate, here’s the usual problem: Binding events that use the iteration count, through elements in an array using a loop.

var elements = [/*elements*/];
var i;

for(i = 0; i < elements.length; ++i){
  elements[i].addEventListener('click',function(event){
    alert(i);
  });
}

Now you’d expect that each element will alert the value of i at the time the handler was attached to the element – WRONG.

Let’s remember that JavaScript is function scoped and not block scoped. The handlers don’t alert the value of i at the time of the iteration. All the handlers use the same outer i and will alert the same value after all iterations (and increments of i)..

The usual way to resolve this issue is to create a closure to simulate a block scope for each iteration. This is usually done by using an Immediately Invoked Function Expression.

var elements = [/*elements*/];
var i;

for(i = 0; i < elements.length; ++i){
  (function(j){
    elements[j].addEventListener('click',function(event){
      alert(j);
    });
  }(i));
}

But this is suboptimal in a way that:

  • Per iteration, you are creating and executing a function as well as creating closures on the way. If you happen to loop through 1k items, you are creating 1k functions and 1k closures. This is bad for memory when used hastily.

  • With this hazard, JSHint will issue a warning that you are doing such and will break your build step (unless you did a --force, or turned off the warning).

  • You could factor out the function and call it per iteration. But that way, you are adding to the globals, aside from the i you just made. If you are namespacing it, it’s an unnecessary namespacing operation just for a very trivial task.

How about jQuery.each()?

We aren’t building a function per iteration, just using the function passed into .each(). It’s not stored as a global, nor namespaced. In fact, it isn’t stored anywhere. It’s just referenced as a function argument inside .each().

But most importantly, each iteration has it’s own scope due to the fact that our code is in a function. Each iteration runs the function, providing a count and the value of each item in the array which is localized inside the executed function.

Thus, this is much better to look at.

$.each(elements,function(i,value){
  element.addEventListener('click', function (event) {
    alert(i);
  });
});

Abstraction of for in and for/while

Normally, you iterate through arrays differently from objects. You use for/while in arrays or array-like objects, while you use for-in for objects. The usual way they look is:

//objects
for(var key in object){

  //skip on non-instance properties
  if(!object.hasOwnProperty(key)) continue;

  //closure for simulated block scope
  (function(key,value){
    /*...*/
  }(key, object[key]));
}

//arrays
for(var i = 0; i < array.length; ++i){

  //closure for simulated block scope
  (function(i,value){
    /*...*/    
  }(i,array[i]));
}

Very messy, don’t you think? Now, let’s do jQuery.each() and see how it looks like:

//object
$.each(object,function(key,value){
  /*...*/
});

//arrays
$.each(array,function(i,value){
  /*...*/
});

Minus the fact that objects use keys, and arrays use indexes, both code looks exactly the same! No need for complicated syntax to differentiate each loop’s purpose. It’s a no-brainer!

Readability

If you take a look at the examples above, which do you think looks more elegant? A multi-doodad code, or a simple block passed into .each()? You decide. For me, jQuery.each() wins in readability.

What do you think?

If you have other ideas, disagree on my views or whatever, just leave a comment or contact me. It’s always good to have some discussion going on.

Here’s the case: You want to use extract keys from an object in JS into an array, but Object.keys is ES5 tech. You could have done loops but unfortunately it’s messy and you’re also avoiding that. Making matters worse, it’s impractical to load another library and you’re stuck with jQuery that has no polyfill for it… or so you think.

Enter jQuery.map(), the polyfill for Array.map which is also ES5 tech. Now, you might think “Oh, that’s just wrong. That’s for arrays.” As of jQuery 1.6, it also runs through objects. So basically, it is similar to jQuery.each() but instead of just running through the collection, it also generates an array depending on what you return from the callback on each iteration. Also, similar to each, it also receives the value and the index/key.

Let:

var foo = {
  bar : 'hello',
  bam : 'world'
};

With Object.keys(), you use it like this and you get an array of keys.

var keys = Object.keys(foo); // ['bar','bam']

With jQuery.map, a similar effect is achieved

var keys = jQuery.map(foo,function(value,key){return key;}); // ['bar','bam']

The magic of jQuery.map is that it also runs through objects, which Array.map() can’t do. It generates an array of results, and it’s callback is given the key which we can return to the generated array. These vital aspects make it a good alternative for Object.keys.

Now you might say “I can do that with jQuery.each()“. Yeah, sure you can, but at the cost of elegance. You lose the one-liner approach.

var keys = [];
$.each(foo,function(key,value){keys.push(key);});