Iterating over an HTMLCollection

I have always expressed my lack of interest in jQuery. I don’t like it as a framework, but I like even less the fact that it contributed to the creation of a wave of bloated websites. There are countless of sites that load jQuery just to do a transition, or to hide an object.

jQuery also contributed to the proliferation of plugins that don’t really do anything other than providing eye candy, but don’t improve the overall usability of a site, sometimes they even worsen it. jQuery also created a culture of instantaneous code, where people think everything is as easy as doing $().

Despite all its faults, jQuery did great things. It hid away the complexities of dealing with the DOM, it helped many people enter the world of Javascript, and it demonstrated that there are better ways to do things.

One of the things I like about jQuery is the fact that you can almost effortlessly apply changes to a collection of elements. Think for example, that you had to move all elements that had a certain class name to the left by 10px. Now, lets say you must do it with javascript. With jQuery you would do something like:


$('.className').css('left', '10px');

Compare that to the amount of code you have to use to do the same thing with vanilla js:


var nodes = document.querySelectorAll('.className');
for (var i = 0; nodes[i]; i++) {
  nodes[i].style.left = "10px";
}

That is not too bad, but it is not as simple as the online jQuery code. The for loop is just boilerplate code. There is a better way to do it:


function iterateCollection (collection) {
  return function(f) {
    for(var i = 0; collection[i]; i++) {
      f(collection[i], i);
    }
  }
}

This is a nice little function that will allow you to iterate over a collection of nodes, or an array even, and then it will call a function passing it the current index, and the element at that index. To call it, you simple do this:


iterateCollection(nodes)(function(node, i) {
  node.style.left = "10px";
});

While it may not be as little as the jQuery code, it eliminates the need for the library. Also, the function can be used with other functions to create more interesting patters.

I am currently working on a DOM library that takes advantage of this kind of patter as an implementation of functional programming for DOM manipulation.

Advertisements

Becareful with isNaN and Type Conversion

As you may know, Javascript is a loosely typed language. It knows about data types, but it just doesn’t care too much about them. This can be both, a good and a bad thing. For this reason, you must always be careful when dealing with different data types, especially because they can be converted from one type to another automatically, which can lead to unexpected results and nasty bugs.

Today I came across such a situation. I was building a form that needs to update itself based on some values, such as number of tickets, and extra donations. When I was checking if there where any extra donation, I was first making sure that the donation value was a number, and not some other value. For that I did this:


if (isNaN(extra)) {
  extra = 0;
}

As you can see, we assume that if the value is not a number, it must be 0, meaning no donation is made. This seems like a good working code, but it is not. It has a few flaws that make it buggy.

Before continuing, you should know that the extra value is used later to calculate the total of the transaction. For that I have a line like this:

grand_total = ticket_price + extra

What happens if the user inputs 3 on the donation field, and the ticket is 100. You would expect the grand total to be 103, but it is not. It is actually 1003. This is because the 3 is a string type, not a number. There are a few ways to convert the 3 from a string to a number, one of them is using parseInt. So, lets add that to the code:


if (isNaN(extra)) {
  extra = 0;
}
extra = parseInt(extra, 10);

Now, we get the right result (103, not 1003). But remember that I told you that the code was buggy? Well, imagine now, that instead of entering a 3, the user leaves the donation field blank. What would happen? Well, grand total will now be NaN...

Why? Because when you do this:

if (isNaN(''))

The empty string is evaluated to false, which evaluates to 0, which has been converted to a number type, which of course is a number. So, now your code inside the if statement is not executed, and extra remains an empty string. But, when you pass an empty string to parseInt it returns NaN, because of course an empty string is not a number, and in this case there is no data conversion to make that empty string into a nice 0. Later when you want to add the ticket price to the extra donation, you are actually trying to add 100 to NaN, which will give you NaN as a result.

In other words, according to isNaN an empty string is a number, but according to parseInt an empty string is not a number, and this is thanks to type conversion.

The solution is quite simple, test the value return by parseInt to see if it is a number:

if (isNaN(parseInt(extra)))

This kind of bugs are easy to miss, and they can result in really bad situations. This is one of the reasons why type conversion is not so cool sometimes.

What Is Currying Useful For?

Have you ever heard of currying? Currying is basically taking a function that takes 2 or more arguments and turning it into one that returns a function that can be called with a single argument. The returned function then returns yet another function which also can be called with a single argument. This continues for as many times as the number of arguments in the original functions. In other words, instead of doing this:


sum(1, 2, 3);

You do this:


sum(1)(2)(3);

But, why would you want to do that? At first sight it does not seem very useful. However, it is.

Imagine you have a function that takes two arguments. The first argument would be a DOM node reference, and the second would be a string. The function takes the string, and sets it as the text content of the element referenced as the first argument. In Javascript the function would be something like this:


function writeToNode(node, value) {
  node.innerHTML = value;
}

The curried version of that function would be something like this:


function writeToNode(node) {
  return function (value) {
    node.innerHTML = value;
  }
}

As you can see writeToNode now returns a function that takes the value as the argument. This function is the one to perform the task. What is the benefit of that? Well, it all actually depends on what you are doing, but think of for example a situation where you want to be able to show a different message depending on some condition:


var nodeRef = writeToNode(node);

if (condition) {
  nodeRef('Condition is true');
} else {
  nodeRef('Condition is false);
}

This example is pretty simple, so the benefit may be not even noticeable, but in a more complex situation they are obvious.

Why would you want to change your code to be like that anyway? Why not just do this:


// Here the function is not curried.
if (condition) {
  nodeRef(node, 'Condition is true');
} else {
  nodeRef(node, 'Condition is false);
}

Well that works well in this example (if you ignore the fact that you are repeating your self there anyway), but what happens when instead of passing a node reference you want to pass an id? The non-curried function becomes this:


function writeToNode(id, value) {
  var node = document.getElementById('id');
  node.innerHTML = value;
}

If you are used to optimizing your code, then I’m sure you already spotted the problem with the function. Every time you call that function, there is DOM interaction, which you should reduce as much as possible. Sure you could use a closure to save a reference to the DOM node, but that brings in its own problems:


var writeToNode = (function() {
  var node;
  return function (id, value) {
    if (!node) {
      node = document.getElementById(id);
    }
    node.innerHTML = value;
  }
}());

By doing this, you’ve accomplished a few things. You’ve made it so that the function only interacts with the DOM once, but you’ve also made it so that the node can never be changed. There are ways to overcome that but they make the function even more complex. Since we are talking about complexity, you have also made the function more complex than it needs to be.

There are many other benefits of currying, but at the end it all comes down to a single simple principle: Always use the best tool for the job. Sure currying has benefits over the example shown here, but there are instances where currying will not be the way to go. So, always look for the best way to accomplish the task at hand.

Links of the Day 12/23/2012

I have some links to share today. I have been too busy lately, so they are just a few. No description today, so just go ahead and click on a link and hope to be lucky!

http://jlongster.com/2012/07/17/ahoy-internet.html

http://www.dustindiaz.com/javascript-curry/

http://stackoverflow.com/questions/113780/javascript-curry-what-are-the-practical-applications

http://osteele.com/sources/javascript/functional/

http://ejohn.org/blog/partial-functions-in-javascript/

http://agile.dzone.com/articles/what-refactoring-and-what-it-0

http://www.angelwatt.com/coding/masked_input.php

http://whattheheadsaid.com/2011/11/javascript-masked-inputs-do-we-need-them

http://git.661346.n2.nabble.com/Git-terminology-remote-add-track-stage-etc-td5648599.html

http://programmers.stackexchange.com/questions/114249/git-what-gotchas-should-newcomers-to-version-control-be-aware-of/114312#114312

http://stackoverflow.com/questions/13622544/how-can-i-version-control-my-little-framework-better/13622839#_=_

http://jeffschuette.com/2012/04/27/designing-in-the-browser/

http://www.alistapart.com/articles/css-positioning-101/

http://webdesign.tutsplus.com/articles/choosing-the-right-font-a-practical-guide-to-typography-on-the-web/

http://net.tutsplus.com/tutorials/html-css-techniques/quick-tip-understanding-css3-gradients/

http://www.rodrigoalvesvieira.com/copy-unix/

http://webdesign.tutsplus.com/articles/design-theory/an-introduction-to-color-theory-for-web-designers/

http://emrahgunduz.com/categories/development/wordpress/wordpress-disable-auto-paragraphing/

getByName, a Javascript Function that Gave Me Trouble

Today I was working on a site that needs to be re-written with a focus on optimization. The old site runs on wordpress, and the task is to take if off from wordpress and build a custom mini engine to run that site and a few others. Since the site needs to load fast, I decided to write all the javascript by hand as opposed to using some of those frameworks that people seem to love.

This morning, as I set to work on the javascript, I thought it would be a good thing to forgo all loop usage and use recursive functions instead, even if just for the sake of doing it. As you know from my posts, I try to be functional on my programming. I believe functions are far superior to objects, although, objects do come in handy sometimes. I also try to follow the little functional programing principles that I know, but I’m still learning. All that I’m going to show you here can be easily, and painlessly accomplished using loops, but what is the fun in that? Also, as you read my code, keep in mind that I am not a pure functional kind of guy. I mix stuff, sometimes out of convenience, and others out of ignorance. I will leave it to you to decided when it might be one or the other.

One of the things that I need to do in the site is to validate a form. I like to set up an array of the fields that are required, this way if I need to add or take out required fields, I can do it easily. In this case the array contains the name of the fields that are required, so at some point I need to get elements by their name. That is where the getByName function comes in handy. (Yes, I know we have query selectors now, but IE is a must on this project).

A first naive attempt to write the function would be this:


var getByName = (function(){
   var iteration = 0;
   var els;
   return function(nme, ctx){
     var c = ctx || document;
     if(typeof els == 'undefined') els =  c.getElementsByTagName('*');// get them only once for better performance.
     var currEl = els[iteration];

     if(!currEl.name){
       iteration ++;
       getByName(nme, c);
     }

     if(currEl.name == nme){
       return currEl;
     }
    
     iteration ++;

     if(iteration == els.length){
       return false;
     }else{
       getByName(nme, c);
     }
   }
 })();

I don’t know if you can spot the problems with that code. They are easy to miss, and cause a lot of trouble. One hint is that the function will most likely not return the element that you are expecting. It took me a long time to figure out what was wrong.

The function looks right. It felt right at some point, and it was frustrating to see it fail over and over again. I felt like those breaking points in firebug were laughing at me so hard that I could almost hear them.

The function that gets executed when you call getByName is the returned function, and this is why I though happened when the function was executed:

1) Determine the context.
2) Fill the els variable with the live object returned by getElementsByTagName, but only if els is undefined. (This function is expensive here, and overkill, read on to see how I solved that problem).
3) Get the element that corresponds to this iteration of the function.
4) If the element has no name attribute, increase the iteration index and call the function again. Start from 1.
5) If the element has a name attribute, check if is the same as the name we are looking for. If so, return the current element.
6) If the name attribute is not the one we are looking for, increase the iteration index.
7) If the index is equal to the amount of element we have, give up and return false. Otherwise, call the function again and start form 1

There is a big hole there. This function will not work unless the very first element in the list of elements is the one we are looking for. In that case this is what happens:

1) current element (first element) has a name attribute. Skip to the next if statement.
2) current element (first element) has a name that is equal to the one we are looking for. Return current element.

There is no fail there.

But if the first element is not the one we are looking for, the function fails. This is what happens:
(Imagine the element we are looking for is the second in the available elements)

IF element has not name attribute:
1) The element (first element) has no name, increase iteration (value: 1) and call the function again.
2) Function is called again. This is the element (second element) we are looking for. Return it.
3) the function call inside the if statement returns the element we are looking for (second element) but it is never caught, and the first function call continues execution.
4) current element (first element) has no name, so currEl.name == nme is false.
5) Increase the iteration index (value: 2).
6) If iteration is not equal to amount of elements available, call the function again. From now on, all calls will fail.
7) Once all elements have been exhausted, continue execution of first call
8) Noting else to do, return nothing.

If element has name attribute, but not the one we are looking for:
1) Element has name attribute. Skip to the next if statement
2) element’s name is not the one we are looking for.
4) increase iteration index (value: 1)
5) If iteration is not equal to available elements, call the function again, else return false.
6) Function is called again. Element is the one we are looking for. Return it.
7) Element is not caught.
8) First function call continues. Nothing else to do, return nothing.

We were able to find the element we were looking for, but it was never caught. A lot more functions to the call are made, and until the last one returns, then the first one continues. But there is nothing else to do, and nothing to return. The function dies, and the element is never returned.

I have oversimplified what happens. In reality, functions can be called on the second if statement, or on the else statement, and every time a function is called, the very first execution is paused, and continues only when the other call returns. This can create a big mess. You can end up with a first call waiting for 2, 3 or maybe more execution to return before continuing. And what is worse, even if any of this subsequent function calls find the element we are looking for, it will never be returned because the one function that returns a value to be caught is the very first execution, and this one is dealing with the first element in the list, and that one is not the one we are looking for. If you are lost, please tell me about it on the comments. IF I see too many people are getting lost, I will make a video explaining this in more detail.

Imagine you have this:
var el = getByName('email', formElement);//formElement is a reference to form element dom node.

el will receive the value returned by the first execution of getByName, and not by the others that are called recursively.

How do we fix this?

A Naive attempt to solve it is to place a return after calling the function again:


var getByName = (function(){
   var iteration = 0;
   var els;
   return function(nme, ctx){
     var c = ctx || document;
     if(typeof els == 'undefined') els =  c.getElementsByTagName('*');// get them only once for better performance.
     var currEl = els[iteration];

     if(!currEl.name){
       iteration ++;
       getByName(nme, c);
       return; //This the line added.
     }

     if(currEl.name == nme){
       return currEl;
     }
    
     iteration ++;

     if(iteration == els.length){
       return false;
     }else{
       getByName(nme, c);
     }
   }
 })();

This is how I initially tried to solve this problem. This fails. I won’t go over the details of how it fails, but it is pretty much a simple variation of why the first one fails.

At this point I still think that what happens is what I explain on my first list of steps:

1) Determine the context.
2) Fill the els variable with the live object returned by getElementsByTagName, but only if it was undefined. (This function is expensive here, and overkill, read on to see how I solved that problem).
3) Get the element that corresponds to this iteration of the function.
4) If the element has no name attribute, increase the iteration index and call the function again. Start from 1.
5) If the element has a name attribute, check if is the same as the name we are looking for. If so, return the current element.
6) If the name attribute is not the one we are looking for, increase the iteration index.
7) If the index is equal to the amount of element we have, give up and return false. Otherwise, call the function again and start form 1

All I get is an error that the field is not defined when I try to use it, so naturally, I think the function is not finding the field, but I want to make sure:


var getByName = (function(){
   var iteration = 0;
   var els;
   return function(nme, ctx){
     var c = ctx || document;
     if(typeof els == 'undefined') els =  c.getElementsByTagName('*');// get them only once for better performance.
     var currEl = els[iteration];

     if(!currEl.name){
       iteration ++;
       getByName(nme, c);
       return;
     }

     if(currEl.name == nme){
       alert(currEl); //This is the line added.
       return currEl;
     }
    
     iteration ++;

     if(iteration == els.length){
       return false;
     }else{
       getByName(nme, c);
     }
   }
 })();

This makes everything more confusing to me because I see an alert. Remember that at this point I haven’t figured out what is happening. In other words, I don’t know what I explained on my other two lists of steps. So I’m thinking that the element is returned, because I see an alert, which means that the content of that if statement is being executed, so the return is happening.

The return is indeed happening, but it happens at a point where it does not get caught. In our analysis we are thinking that the element we are looking for is the second in the list, so when it gets returned, the initial function call continues. The value returned is never caught. So this is what happens:

var el = getByName(); <- does not find element. Eventually return nothing.
            getByName(); <-this one finds the element, and returns it.

Notice how the second function call returns the element to the first one. The first one does not catch and return the returned value, but instead continues executing, and returns nothing because it finds nothing. That “diagram” is very simple, but it helps visualize what is happening. In reality, it is likely there will be more nested calls. The first call will just ignored their returned value, and at the end return nothing.

Once I figured that out, it was easy to solve the problem. All you need to do is store the value somewhere that will not get lost, then later in the function check if that value has been set, if so, return it. This way, the first call will have access to that value:


var getByName = (function(){
  var iteration = 0;
  var els;
  var el;
  return function(nme, ctx){
    var c = ctx || document;
    if(typeof els == 'undefined') els =  c.getElementsByTagName('*');// get them only once for better performance.
    var currEl = els[iteration];

    if(!currEl.name){
      iteration ++;
      getByName(nme, c);
    }

    if(currEl.name == nme){
      el = currEl;
      iteration = 0;
    }
    if(typeof el !== "undefined" && el.name !== nme){
      el = undefined;
    }
    if(typeof el !== "undefined"){
      return el;
    }

    iteration ++;

    if(iteration == els.length){
      return false;
    }else{
      getByName(nme, c);
    }
    return el;
  }
})();

I said I would tell you how to solve the getElementsByTagName problem. It is quite simple, if no context is provided (ctx) then there is no other option. IF context is provided, and it is a form, use form.elements instead. Otherwise no option.

I will not go into much detail about the function. That function seems to work, but I don’t like how it has a few points of potential failure, especially because of all the calls that happen. I think you could even end up with a calls tree that would be hard to follow. But yesterday, when I started writing this post, I thought it was good enough. I was ready to leave it like that, but the more I though about it, the more it bothered me. There must be a better way to do it. Today I wrote that better function.

A better getByName:

Today I decided to write a better function. First, lets get rid of those persistent values.

The closure creates a few persistent values. That is what we wanted, because we could access the same values from different function calls, but it creates problem because the values would be kept even after the value was returned. That is why we had to reset the iteration index. This could potentially create problem if the iteration index is not reset properly for whatever reason. Whit that mess of a code that I had, it could easily happen.

In order to get rid of the persistent values, we need to get rid of the self-executing functions, which actually makes the code easier to read. In fact, we get rid of the whole function, and start from scratch.

This is the new function:


function getByName2(name, context, i){
  i = i || 0;
  var c = ( (typeof context === 'string') && document.getElementById(context) ) || context;

  if(!c) return false;

  if(c.elements[i].name === name){
    return c.elements[i];
  }else{
    i++;
    return getByName2(name, c, i);
  }
}

Notice that it looks noting at all like the previous one. That is because it was written entirely from scratch.

There are a few trade-offs with this function.
1) context is required, either as the id for the form element where the element is, or as a DOM element object reference.
2) since there are no persistent values, the collection of elements is searched on every iteration. This could present a little performance penalty, but the function is still potentially faster than the previous one.

There is some room for improvement. For example, we could make context optional, or find a way to cache the list of elements so they are not searched for on every iteration.

What do you think of this new function? Definitely much better than my first naive attempts. Do you see a point of failure that I’ve missed?

Links of the day 12/12/12

Some interesting links today:

Javascript:
http://soft.vub.ac.be/~tvcutsem/invokedynamic/presentations/Tradeoffs_WGLD2012_Austin.pdf – Js Proxies (PDF)

Microsoft:
http://arstechnica.com/gadgets/2012/12/in-bringing-office-to-ios-microsoft-is-playing-a-dangerous-game/ – Is MS making a mistake by bringing Office into iOS?

Security:
http://seclists.org/bugtraq/2012/Dec/81 – IE vulnerability allows an attacker to track your mouse movements.
http://arstechnica.com/security/2012/12/internet-explorer-vulnerability-lets-hackers-track-your-mouse-movements/ – More on the IE vulnerability.
http://arstechnica.com/security/2012/12/new-mac-trojan-tricks-users-into-paying-pricey-cell-phone-fees/ – A trojan for the mac that could trick you into paying pricey cellphone fees.

Web development:
http://laurakalbag.com/display-none/ – Don’t hide content on mobile, and other advices.

VIM:
http://www.youtube.com/watch?v=Umb59mMvCxA – Nice VIM multi-cursor show-off.

PC:
http://arstechnica.com/gadgets/2012/12/299-version-of-acers-c7-chromebook-kind-of-defeats-the-purpose/ – Why you should by the cheap version of acer’s C7.

Interior Design:
http://www.home-designing.com/2012/12/japanese-style-minimalist-inspiration – Do it, like the Japanese do.

Other:
http://www.stumbleupon.com/su/1xcpkG/www.elpesonuestro.com/2012/01/20/pobres-de-nosotros-los-mexicanos/ – About retirement founds in Mexico. (Spanish)
http://arstechnica.com/business/2012/12/freedompop-launches-free-home-wireless-to-compete-with-low-end-dsl/ – free home wireless by freedompop
http://arstechnica.com/tech-policy/2012/12/dotcom-case-becoming-one-of-the-most-expensive-in-new-zealand-history/ – Dotcom is costing New Zealand Millions.
http://arstechnica.com/business/2012/12/dish-gets-fcc-approval-to-build-next-generation-lte-network/ – Dish to build next generation LTE network by 2016

Links of the day 12/11/2012

Yet another list of links. The last list is also marked as 12/11/2012. When I did it it was past 12, and I forgot to subtract 1 from the date. I hope it is not too confusing.

HTML 5
http://davidwalsh.name/pointer-media-query – Quick intro to the pointer media query.

Security:
http://arstechnica.com/security/2012/12/dexter-malware-steals-credit-card-data-from-point-of-sale-terminals/ – The alert word for a malware that steals credit card data from point of sale terminals.

WordPress:
http://codex.wordpress.org/Version_3.5 – Version 3.5 is out!

Javascript:
http://rmurphey.com/blog/2012/12/10/js-conditionals/ – Nothing new about if statements, but still worth reading for a good memory refresh.

Github:
https://github.com/blog/1302-goodbye-uploads – No more uploads on github.

Other:
http://arstechnica.com/business/2012/12/netflix-says-google-fiber-is-most-consistently-fast-isp-in-america/ – Netflix says google fiber is the fastest ISP in America. Lucky those who have it.
http://alt1040.com/2012/12/google-chromebooks-sector-educativo – New $99 google laptops. (Spanish)
http://alt1040.com/2012/12/darpa-espuma-hemorragias – New foam technology to stop internal bleeding on wounded soldiers. (Spanish)

Links of the day 12/11/2012

I have been just sharing links these last few posts, and sadly, today is not the exception. I am aware there are a few posts that need to be written, and I need to continue on that series that I started about building AIR Apps, but time has just not been too kind with me lately. Anyway, I hope this links can keep you busy.

Javascript:
http://davidwalsh.name/documentfragment – Just a quick intro to document fragment.
http://davidwalsh.name/deferred – Javascript defer for a cleaner code.
http://www.sitepoint.com/get-started-with-three-js/ – Getting started with three.js
http://blog.millermedeiros.com/stop-writing-plugins-start-writing-components/ – Plugins VS Components. Interesting.
http://blog.millermedeiros.com/namespaces-are-old-school/ – Namespaces are old school, use modules.
http://blog.millermedeiros.com/amd-is-better-for-the-web-than-commonjs-modules/ – A look into why AMD is better than commonjs modules. Is it?

VIM:
blog.millermedeiros.com/tag/vim/ – Improved VIM status bar. Nice!

HTML 5
http://davidwalsh.name/phone-link-protocol – The phone link protocol.
http://davidwalsh.name/vibration-api – The vibrating API. Lets hope it does not get abused.

WordPress:
http://davidwalsh.name/ssl-wordpress – Quick and easy way to force SSL on wordpress sites.
http://dzineblog.com/2012/12/best-practices-for-keeping-wordpress-clean-secure.html – WordPress security best practices.

Interior Design:
http://www.home-designing.com/2012/12/toblerone-house-brazil
http://www.home-designing.com/2012/12/super-small-space-living-inspiration-ikea

Ubuntu
http://www.atareao.es/ubuntu/conociendo-ubuntu/quieres-aprender-a-crear-paquetes-para-ubuntu/ – How to create Ubuntu packages. (Spanish)

Design:
http://dzineblog.com/2012/11/33-new-freebie-buttons-and-icon-sets-released-in-autumn-2012.html – Free icon sets.

Ruby:
http://ruby-python.com.ar/ruby/ – A ruby tutorial that I have not yet followed, but I share in case you are interested. (Spanish)

Other:
http://davidwalsh.name/twitter-cards – Nice explanation on how to create twitter cards.
http://creativefan.com/black-and-white-backgrounds/ – Black and white backgrounds. Mostly pictures, and some of them are not really B&W, but still interesting.
http://alt1040.com/2012/12/twitter-rastrea-webs – Twitter keeps track of the sites you visit. And how to stop it. (Spanish)
http://build-podcast.com/ – A postcast about development tools.
http://www.mightydeals.com/ – A website that seems to offer good deals on resources for web professionals.

Enjoy the readings, and don’t hate me for posting nothing but links these last few rounds.

Links of the Day – 11/15/2012

Whit this post I start a new category on the blog. I will be sharing the URLs to articles that I’ve read on that day or the previous days and that I found interesting. So, here they are:

Design and Web Development:
http://webdesign.tutsplus.com/articles/designing-in-browser-a-manifesto/ As the title says, a manifesto on web designing done directly on the browser. Via search on duckduckgo.com (yeap, I don’t use google! Say no to the bubble!)
http://www.microsoft.com/en-us/download/details.aspx?id=11575 Get free virtual machines for testing on old versions of IE. Via Hacker News

Programming:
http://www.codewa.rs/ A cool site for programmers. Just check it out!
https://speakerdeck.com/kennethreitz/python-for-humans A presentation on Python programming language.
http://www.cs.berkeley.edu/~vazirani/algorithms/all.pdf A book on algorithms. Via Hacker News
https://code.google.com/p/android/issues/detail?id=19827 A bug report that causes touchmove and touchend events not to be fired if preventDefault is not called on touchstart. Found after dealing with this problem on a project.
http://www.ofbrooklyn.com/2012/11/13/backbonification-migrating-javascript-to-backbone/ Developing with backbone.js via Hacker News.

Security:
http://pixus-ru.blogspot.ru/2012/11/hack-any-skype-account-in-6-easy-steps.html Cracking Skype accounts. Via Hacker News
http://www.wired.com/gadgetlab/2012/11/ff-mat-honan-password-hacker/ Password are obsolete. Via Hacker News.
https://plus.google.com/101960720994009339267/posts/hoJdanihKwb Rob Pike on OOP. Via Hacker News.

Other Interesting Articles:
http://www.bbc.co.uk/news/magazine-20243692 An article about eating habits through history. Via Hacker News.
https://plus.google.com/105363132599081141035/posts/Lce7wEJApEr About selling games on the conventional way. Via Hacker News.
http://ninjasandrobots.com/facebook-pages-nest-thermostat Facebook likes and how they could spam your friends. Via Hacker News.

Infinite Function Calls: Javascript

I was about to sleep last night, when a nice pattern came to my mind. I had already played with something similar in the past, but not to the level that I’m playing now. I call it the Infinite Function Calls Pattern. I am unaware if anyone has come up with this pattern before. All I know is I have never seen it before.

A function in Javascript can return anything, even another function. So you can do this:


var a = function(){
    alert('Hello');
    return function(){
        alert('World');
    }
}

If you follow this blog regularly, you should already be familiar with that pattern. What you may or may not know is that you can execute the returned function right away:

a()();

Pretty Cool! This kind of thing can be really useful in certain situations. However, you can only chain as many immediate calls as returned functions. This is where the new pattern improves this one.

Lets see an example:


var a = function(n){
    n++;
    alert(n);
    a = function(){
        n+=n;
        alert(n);
        return a;
    }
    return a;
}

a(1)()()()()()()()()()()();

You can basically add as many immediate calls as you want. I still haven’t come up with a real-life situation where we could use this pattern, but it is nice to know that it exists. Lets see another interesting example:


var a = function(n){
    n++;
    alert(n);
    a = function(m){
        m = m || n;
        n+=m;
        alert(n);
        return a;
    }
    return a;
}

a(1)()(6)()()()()(23);

Here we are passing parameters to the function and it reacts differently than in the previous example. Based on this, we could create something like this to generate markup:


var p = function(content){
    var _p = document.createElement('p');
    var _t = document.createTextNode(content);
    _p.appendChild(_t);
    document.body.appendChild(_p);
    
    return p;
}

p('Hello')('World')('My Name Is')('My Name Is')('Slim Shaddy');

As you can see, here we don’t even need to redefine the function like in our previous examples. As long as the function returns itself we can call it infinitely:


var a = function(n){
    alert(n);
    return a;
}

a(1)(2)(3)(4)(5);

The reason we were redefining the function before was to create a closure over n so that we could re-use it as many times as we wanted. That is a really powerful way of using this pattern, but we will come back to that later on another post. For now, lets expand our markup generating function a bit more:


var mk = function(content,tag){
    tag = tag || 'p';
    var el = document.createElement(tag);
    var cont = document.createTextNode(content);
    el.appendChild(cont);
    document.body.appendChild(el);
    
    return mk;
}

mk('Hello','div')('World', 'i')('My Name Is', 'strong')('My Name Is')('Slim Shaddy');

I changed the function name and the internal variables, but most of the function is still the same. However, we can now specify what kind of element we want to generate. There is a lot of room for improvement on this function, for example, you could specify what element you want the generated markup to be appended to.

This pattern could be used for many more other tasks, like lazy recursion, or data evaluation. If you are feeling particularly masochist, you could even use eval to generate a different amount of function calls on the fly:


var mk = function(content,tag){
    tag = tag || 'p';
    var el = document.createElement(tag);
    var cont = document.createTextNode(content);
    el.appendChild(cont);
    document.body.appendChild(el);
    
    return mk;
}

var calls = 500,
    cont = 'foo',
    exec = 'mk';
    
for(var i = 0; i < calls; i++){
    exec += '("' + cont + '")';
}

eval(exec);

Although, I don’t recommend this.

As you can see, this is a very interesting pattern that allows for many interesting things to be made. If you come up with some great ideas of where this could be useful, let us know via the comments form.