Javascript – Fake Arrays

A friend of mine gave me a great challenge. Find out how jQuery did to return objects that behave like arrays but that are not arrays! The aim of this article is to find out how Firebug and Web Inspector can display an object with the bracket notation.

$('a')
>> [<a href="http://vjeux.com/">vjeux</a>, <a href="http://google.com/">google</a>]

Not an Array!

First, let’s make sure that this is really not an Array. If you wonder why just not subclassing the array, there are many reasons explained on this great article.

// Easy way
typeof $('a')
>> "object"
 
// Normal way
$('a') instanceof Array
>> false
 
// Duck typing ...
$('a').indexOf
>> undefined
 
// Object toString
// http://whattheheadsaid.com/2010/10/cross-context-isarray-and-internet-explorer
Object.prototype.toString.call($('a'))
>> "[object Object]"
 
// http://ajaxian.com/archives/isarray-why-is-it-so-bloody-hard-to-get-right
$('a').constructor
>> function Object() { [native code] }
 
// ES5 Way
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/isArray
Array.isArray($('a'))
>> false

// Normal way
$(‘a’) instanceof Array
>> false

// Duck typing …
$(‘a’).indexOf
>> undefined

// Object toString
// http://whattheheadsaid.com/2010/10/cross-context-isarray-and-internet-explorer
Object.prototype.toString.call($(‘a’))
>> "[object Object]"

// http://ajaxian.com/archives/isarray-why-is-it-so-bloody-hard-to-get-right
$(‘a’).constructor
>> function Object() { [native code] }

// ES5 Way
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/isArray
Array.isArray($(‘a’))
>> false

Testing …

Obviously Firebug and Web Inspector must use another technique. What they need to display an Array is only the length property and the keys [0 .. length-1]. So let’s try!

({0: 42, 1: 666, length: 2})
>> Object { 0=42, 1=666, length=2 }

This is obviously not working 🙁

In Source the Truth Lies!

Hopefully, both Webkit and Firebug are open source projects, this means that anyone can browse the source code and therefore tell exactly what happens behind the scene.

// Web Inspector Source Code
// http://trac.webkit.org/browser/trunk/WebCore/inspector/front-end/InjectedScript.js#L409
 
// FireBug's array detection.
if (isFinite(obj.length) && typeof obj.splice === "function")
  return "array";

// FireBug’s array detection.
if (isFinite(obj.length) && typeof obj.splice === "function")
return "array";

We can see that Duck Typing is being used. It is now really easy to trick Firebug and Web Inspector to make them believe that your objects are arrays! Only 3 small rules are required:

  • [0 .. length – 1]: Array elements
  • length: Set to a positive integer
  • splice: Any function (even empty)

And here is the demo 🙂

({0: 42, 1: 666, length: 2, splice: function() {}})
>> [42, 666]

WoWTal.com Cataclysm

Check out the updated World of Warcraft talent calculator I’ve been working on 🙂

// Add VideoJS to all video tags on the page when the DOM is ready
VideoJS.setupAllWhenReady();

Popularity System

In Starcraft 2, the Custom Maps are being listed by popularity. The popularity is the number of times the map has been played for more than 5 minutes during the last 12 hours.

As I am running the website sc2mapster.com, I would like to have this listing. This would let the players know what are the popular maps in the other regions (US, EU, KR …) but also let them find quickly the maps they have played to leave comments!

Getting the list!

Bad news, the listing is only available inside the game. And with the anti-hack measures Blizzard is taking, this is not a viable solution to extract them from the client. So we have to find another solution!

Hopefully, there’s one. Blizzard is updating a website called Battle.net with the profiles or every player. In the player profile there are his latest 24 games played.

Since we can’t parse all the characters (there are more than 1.6 millions as I speak) we are going to parse as much as we can picking them randomly. And we just add +1 for the couple [Map, Date]. As a result for each map we get the an approximation of number of times it has been played.

As you can see there’s a hole around September 9, this is a side-effect of the 24 latest played limit. The data has been gathered for 2 days between the 15 and 16. Before the 9 you can see all the casual players that don’t play too often and who’s 24 limit has not been reached. Between the 11 and 13 the frequent players and after the hardcore ones.

However those artifacts are likely to disappear with a constant spidering.

Does it match?

Now that we’ve got a lot of data, the question that everyone’s waiting … Does it match the popularity listing!


Calculated Popularity | Position Difference | Real Popularity

As you can see, the top 12 maps are the same with some small ordering differences. However since the order is constantly changing, that’s not that a big issue.

In order to get those results about 30 000 players have been parsed and the top popular map Nexus Wars has 2200 points (Real popularity is about 6000). Instead of using the data from the last 12 hours we used the data from the current day and the day before (the granularity of Battle.net listing is 1 day).

Conclusion

It was really hard to know if this method was going to give similar results as the ingame popularity. The only way to make sure of it was to test! I’ve setup the website scladder.com (recycled domain name) to show the values. However, due to the number of requests needed, I am probably not going to keep the spider running for a long time.

I just showed you that it was possible to datamine websites in order to obtain useful statistics 🙂 I hope you like it!

I have integrated the LRDE (EPITA Research & Development Lab) few months ago as a student and this is my first research presentation.

Climb – A Generic and Dynamic Approach to Image Processing

Abstract: “Climb is a generic image processing library. A case study of the erosion algorithm from mathematical morphology highlights the issues of a non-generic implementation. Structures such as Image, Site Set and Accumulator are defined to solve them. Genericity is even increased by the concept of Morphers: a way to alter the communication between an object and the outside world. All these additions are done using the dynamic aspect of Lisp that allows for rapid prototyping.”

Presentation

The oral presentation is in French. The slides (Download) are not readable in the video due to the poor recording quality, please scroll the slideshare at the same time you are viewing the video.

Technical Report

Along with the presentation, I have written a 20-pages technical report (Download).

Project – SC2Mapster

Let’s get back three months before the beginning of my internship. Blizzard just released the private beta of the long waited real-time strategy (RTS) game Starcraft 2, a remake of their first extremely-successful game. I wanted to run a website for this promising game and started SC2Mapster.com. It is focused around the Map Editor of the game.

Start

I spent countless hours working on custom maps for Warcraft 3, the other RTS franchise from Blizzard. Therefore I decided to run SC2Mapster. I did not start the website from nothing, we adapted a custom web framework called CurseForge that we use for the addon developers. It has built-in support for file hosting, forums, announcements, wiki, etc… Everything needed!

Great, now it’s time to get people in. At the time of the launch there were three kinds of competitors: important Warcraft 3 websites about custom maps such as HiveWorkshop, WC3Campaigns or Nibbits, huge portals about Starcraft 2 with a mapping part like TeamLiquid and new sharks like us.

The strategy that I use was to behave like a user. The map editor was not yet released but we could analyze the already existing maps. During this period I started contacting the few users that were hacking the maps and told them to come on the IRC. At the same time I started an effort to document all the parts of the editor. In order to get traffic from outside, I created the first custom map that was not just a basic modification of existing maps: Mapster TD. It has been linked on various non-mapping related websites and the video was viewed 35 000 times.

News

In the early days of Starcraft 2, it was really difficult to know what happened in the modding community. Everyone was working on his own and did not communicate with each other. I spent a lot of time seeking for websites and people that were acting in the area. Since I found some cool projects, I started listing those in the front page of SC2Mapster.

Quickly, people started to visit the website as they wanted to know about the Starcraft 2 map making. At the beginning the majority of links were sending people outside of SC2Mapster. Interestingly, people sticked to our website. They started contributing on the forums thanks to the news I was writing.

As it shows great results, I decided to start writing news at a daily rate. This was quite a challenge as I never had any experience in journalism. At first this was hard. I did not really know where to find good source of information. There were many interesting projects going on but they rarely provided material that was good to show. I started contacting people and ask them to make content that I could news. In 6 months, not a single person did not answer me or did not wanted to do it, this was really impressive!

I found that the best way to show off maps was video. The other options are text or screenshots. Text is painful to read and does not represent well a map. Screenshots are better but it is really hard to show liveliness with it. It is also painful to browse more than 5 screenshots. I decided to use video as primary support, if a project does not have a video then it will not be newsed. About a month after the adoption of that guideline, a lot of project started to do videos. It substantially improved the communication quality of a lot of projects.

Contest

A contest is an effective way to stimulate a community. The Starcraft 2 map editor being powerful, it gives wide range of areas to explore. When a contest takes place, this is the opportunity to make everyone focus on the same objective for a given period of time. This is also a motivator since the entries will be rated and a winner elected.

Contests were organized at a rate of two per month. One week to do the entry, one week to vote. As you can see, all the thirteen contests were unique.

  • World of Warcraft Boss Contest September 21st, 2010
  • Epic Battle Scene Contest September 2nd, 2010
  • Blizzard Custom Map Contest August 13th, 2010
  • User Interface Contest August 4th, 2010
  • Minigame Contest July 21th, 2010
  • Creature Contest June 29th, 2010
  • Wallpaper Contest June 17th, 2010
  • Spells Contest June 9th, 2010
  • 3D Modeling Contest May 26th, 2010
  • Melee AI Contest May 25th, 2010
  • Cut Scene Contest May 14th, 2010
  • Clock Contest May 2nd, 2010
  • Inventory Contest April 11th 2010

How to make a good contest

This is hard to organize a good contest.

The most important thing is to define the objective: stimulate the community. The community as a whole needs to participate. The rules of the contest should welcome both the newcomer and the expert. The challenge lies in the huge difference in skill between both, we want to make sure that everyone has a chance to win.

The first step toward this goal is to limit the time of the contest. Giving a week is enough for people to make interesting things, but not enough for a polished product. Therefore all the entries will be prototypes. The concept submission will be remain important factor. A week is also short enough so that people will start working right away, and not be tempted to do it later on, and then forget.

Then the subject is important. It must be balanced between specificity and openness. Each contest should have a specific theme so people have the feeling that they are competing on the same field. But it should give the opportunity to innovate. You want to vary the themes of your contests and make them cover all the features of the domain.

Since not everyone will participate, we make people vote for the best entry. This voting phase will show all the entries to the community. The results will be biased as people who vote will probably judge only with the provided videos and not test the map. But this is not important as the goal is to get people involved!

Incentives. I found out that people would gladly enter the contest even if there was no real prize. Being highlighted in the front-page of sc2mapster is motivating enough. If we were to put cash prizes, people would be less likely to do it for fun but try instead to abuse the system to win.

Finally, listen to the community. A lot of people came to me with contest ideas. However take care, most of them will not be good contests. Make sure you adapt them to fit all the rules I highlighted and eventually they will be good to go.

Moderation

The site got bigger. At one message per minute at peek hours, it was no longer able to review all the messages that were posted. Therefore it became difficult to moderate the forums.

We made a call for moderators and we were really surprised that 40 people applied. It was a tough decision to chose them. In the end one moderator was assigned for each forum, and three for the most active one. Using the activity count and their preferences we picked 13 out of all the applicants.

I had great faith in the moderators we took and wanted to give them the ability to conduct a project of their choice. It would be advertised on the front-page and labeled as an official SC2Mapster project. However this failed. This was more perceived as a constraint instead of an opportunity. It also confused them as to what were their role.

Another mistake we made was a lack of communication. We did not force the moderators to go into our private IRC channel. Therefore we were not able to create a group feeling. This was amplified by the timezone differences: the Europeans rarely talked to the Americans.

Even if I wasn’t a really good manager, they did an awesome job at moderating the forums.

Javascript – Slug

A slug is a way to represent a title with a limited charset (only lowercase letter and dash) to be inserted in the url. Even if it is a common function there is no good enough implentation when you Google for it.

Here are the features I needed:

  • No multiple dashes. ---- is converted to -
  • No wrapping dashes. -title- is converted to title
  • Basic support for internationalization. Coût d'éclat is converted to cout-d-eclat Don’t look at the spelling mistake!
  • Basic support for common signs. 13$ & 12€ is converted to 13-dollar-and-12-euro

Demo

You can try the demo and see if it fits your needs.
var keys = keys || function (o) { var a = []; for (var k in o) a.push(k); return a; };
slug = function (string) {
// var accents = “àáäâèéëêìíïîòóöôùúüûñç”;
var accents = “u00e0u00e1u00e4u00e2u00e8”
+ “u00e9u00ebu00eau00ecu00edu00ef”
+ “u00eeu00f2u00f3u00f6u00f4u00f9”
+ “u00fau00fcu00fbu00f1u00e7”;
var without = “aaaaeeeeiiiioooouuuunc”;
var map = {‘@’: ‘ at ‘, ‘u20ac’: ‘ euro ‘,
‘$’: ‘ dollar ‘, ‘u00a5’: ‘ yen ‘,
‘u0026’: ‘ and ‘, ‘u00e6’: ‘ae’, ‘u0153’: ‘oe’};
return string
// Handle uppercase characters
.toLowerCase()
// Handle accentuated characters
.replace(
new RegExp(‘[‘ + accents + ‘]’, ‘g’),
function (c) { return without.charAt(accents.indexOf(c)); })
// Handle special characters
.replace(
new RegExp(‘[‘ + keys(map).join(”) + ‘]’, ‘g’),
function (c) { return map[c]; })
// Dash special characters
.replace(/[^a-z0-9]/g, ‘-‘)
// Compress multiple dash
.replace(/-+/g, ‘-‘)
// Trim dashes
.replace(/^-|-$/g, ”);
};

Code

var keys = keys || function (o) { var a = []; for (var k in o) a.push(k); return a; };
 
var slug = function (string) {
//  var accents = "àáäâèéëêìíïîòóöôùúüûñç";
  var accents = "u00e0u00e1u00e4u00e2u00e8"
    + "u00e9u00ebu00eau00ecu00edu00ef"
    + "u00eeu00f2u00f3u00f6u00f4u00f9"
    + "u00fau00fcu00fbu00f1u00e7";
 
  var without = "aaaaeeeeiiiioooouuuunc";
 
  var map = {'@': ' at ', 'u20ac': ' euro ', 
    '$': ' dollar ', 'u00a5': ' yen ',
    'u0026': ' and ', 'u00e6': 'ae', 'u0153': 'oe'};
 
  return string
    // Handle uppercase characters
    .toLowerCase()
 
    // Handle accentuated characters
    .replace(
      new RegExp('[' + accents + ']', 'g'),
      function (c) { return without.charAt(accents.indexOf(c)); })
 
    // Handle special characters
    .replace(
      new RegExp('[' + keys(map).join('') + ']', 'g'),
      function (c) { return map[c]; })
 
    // Dash special characters
    .replace(/[^a-z0-9]/g, '-')
 
    // Compress multiple dash
    .replace(/-+/g, '-')
 
    // Trim dashes
    .replace(/^-|-$/g, '');
};

var slug = function (string) {
// var accents = "àáäâèéëêìíïîòóöôùúüûñç";
var accents = "u00e0u00e1u00e4u00e2u00e8"
+ "u00e9u00ebu00eau00ecu00edu00ef"
+ "u00eeu00f2u00f3u00f6u00f4u00f9"
+ "u00fau00fcu00fbu00f1u00e7";

var without = "aaaaeeeeiiiioooouuuunc";

var map = {‘@’: ‘ at ‘, ‘u20ac’: ‘ euro ‘,
‘$’: ‘ dollar ‘, ‘u00a5’: ‘ yen ‘,
‘u0026’: ‘ and ‘, ‘u00e6’: ‘ae’, ‘u0153’: ‘oe’};

return string
// Handle uppercase characters
.toLowerCase()

// Handle accentuated characters
.replace(
new RegExp(‘[‘ + accents + ‘]’, ‘g’),
function (c) { return without.charAt(accents.indexOf(c)); })

// Handle special characters
.replace(
new RegExp(‘[‘ + keys(map).join(”) + ‘]’, ‘g’),
function (c) { return map[c]; })

// Dash special characters
.replace(/[^a-z0-9]/g, ‘-‘)

// Compress multiple dash
.replace(/-+/g, ‘-‘)

// Trim dashes
.replace(/^-|-$/g, ”);
};

Bonus

If you are bored, here is a little exercise for you. Can you find a and b such as

a >= b && a < = b
// true
 
a == b
// false

a == b
// false

Project – WoW Genuine

Working on the World of Raids Guild Recruitment I needed to make sure the user was really member of the guild he claimed to represent. Since there is no official API and we don’t want to ask for the user login and password, we had to find an other way.

The idea is to take advantage of the official Armory. When the user logs off the game, his character profile is updated on the website. To make sure the user is who he pretends to be, we are going to ask him to make a change on his character, wait for the armory to update and verify.

Since it’s a tool that can be useful to anyone, we decided to make it a standalone service with an open API. If you have a World of Warcraft website and feel the need to verify that your users are genuine, this is your chance!

It has been in activity since the launch of the recruitment tool. So far 100 conflicts have been automatically resolved thanks to this tool.

Check out WoW Genuine.com.

Javascript – Ajax Binary Reader

BinaryReader is buggy and no longer maintained. Check out jDataView for an up to date version.

With WebGL coming in, it is important to be able to deal with binary data files like the models. Since there is no such thing on the internet right now I decided to make my own. The javascript BinaryReader library tries to mimic the C# BinaryReader.

The code is mostly based on the binary-parser class from Jonas Raoni Soares Silva. I’ve added the position management and re-factored the code to remove the with syntax.

In order to load a file into a string, you have to add req.overrideMimeType('text/plain; charset=x-user-defined'); in the Ajax XMLHttpRequest. To read more about this technique, see the Mozilla Developer Center. Here is an overview of the compatible browsers.

  • Chrome 4.0.295.0: Works
  • Firefox 3.5.7: Works
  • Safari 4.0.4: Works
  • Internet Explorer 8: Does not work. Doesn’t have the overrideMimeType method.
  • Opera 10.10: Does not work. Have the overrideMimeType method but doesn’t take it in account.

I hope this will help you to parse binary files!

BinaryReader is buggy and no longer maintained. Check out jDataView for an up to date version.

Download

API

Constructor

  • new BinaryReader(data: String) – Create a BinaryReader with the specified file.

Read Methods

  • BinaryReader.readChar()
  • BinaryReader.readString(length: Number)
  • BinaryReader.readInt8()
  • BinaryReader.readUInt8()
  • BinaryReader.readInt16()
  • BinaryReader.readUInt16()
  • BinaryReader.readInt32()
  • BinaryReader.readUInt32()
  • BinaryReader.readUInt32()
  • BinaryReader.readFloat()
  • BinaryReader.readDouble()

Position Methods

  • BinaryReader.seek(pos: Number) – Go to a specific position (in Byte) in the file
  • BinaryReader.getPosition() – Returns the actual position (in Byte) in the file
  • BinaryReader.getSize() – Returns the size (in Byte) of the file

Exception

  • Error(“Index out of bound”) – When you try to read something that is beyond the end of the file.
BinaryReader is buggy and no longer maintained. Check out jDataView for an up to date version.

Example – Demo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Code from https://developer.mozilla.org/En/Using_XMLHttpRequest#Receiving_binary_data
function load_binary_resource(url) {
	var req = new XMLHttpRequest();
	req.open('GET', url, false);
	// The following line says we want to receive data as Binary and not as Unicode
	req.overrideMimeType('text/plain; charset=x-user-defined');
	req.send(null);
	if (req.status != 200) return '';
	return req.responseText;
}
 
// Load the file
var file = load_binary_resource('author.gif');
 
// Create the Binary Reader
var reader = new BinaryReader(file);
 
// Read some informations
var tag		= reader.readString(6);
var width	= reader.readUInt16();
var height	= reader.readUInt16();
 
// Move around the file and try to read what is there
reader.seek(parseInt('FA', 16));
var random	= reader.readFloat();
 
console.log(
	tag,	// GIF89a
	width,	// 16
	height,	// 16
	random	// 66.01171875
);

// Load the file
var file = load_binary_resource(‘author.gif’);

// Create the Binary Reader
var reader = new BinaryReader(file);

// Read some informations
var tag = reader.readString(6);
var width = reader.readUInt16();
var height = reader.readUInt16();

// Move around the file and try to read what is there
reader.seek(parseInt(‘FA’, 16));
var random = reader.readFloat();

console.log(
tag, // GIF89a
width, // 16
height, // 16
random // 66.01171875
);

Existing Dispatch Methods

Dispatch is the process of mapping a function call to a specific function based on its arguments. Most of the time this is done at runtime through the binding phase, however it usually lacks of modularity.

Dispatch by Type

The first way dispatch has been implemented is through function overloading. Two functions share the same name and depending on the type of the argument, a choice will be made to call the right one.

int   sqr(int i)   { return i * i; } // int version
float sqr(float i) { return i * i; } // float version

When entering the Oriented Object world, there is a more powerful way to dispatch that is not only based on the type but also the type hierarchy. You can allow an object of type A to use the method implementation of one of its children.

class A { public: virtual void print() = 0; };
 
class B : public A { public: void print() { std::cout < < "B" << std::endl; }; };
class C : public A { public: void print() { std::cout < < "C" << std::endl; }; };
 
void doPrint(A& a) {
  // A doesn't have a definition of the print method
  // There is an implicit dispatching to determine which of the B::print or C::print 
  // will be called. This is done at runtime
  a.print();
}

class B : public A { public: void print() { std::cout < < "B" << std::endl; }; };
class C : public A { public: void print() { std::cout < < "C" << std::endl; }; };

void doPrint(A& a) {
// A doesn’t have a definition of the print method
// There is an implicit dispatching to determine which of the B::print or C::print
// will be called. This is done at runtime
a.print();
}

This is a single dispatch since we could see the print function this way: void print(B this) { ... }. In C++ we are limited to only one dispatch, even if Stroustrup proposed a way to support multimethods in C++. The main problem is that it’s being limited to types.

Dispatch by Constant Value

There are ways to use other criteria in order to dispatch, for example the use of numerical constants. In C++ the way to do it is to use templates.

// General case
template < int N >
struct fact {
  enum { value = N * fact< N - 1 >::value };
};
 
// Specialization for n = 0
template <>
struct fact< 0 > {
  enum { value = 1 };
};

// Specialization for n = 0
template <>
struct fact< 0 > {
enum { value = 1 };
};

You have a code that will run differently depending on the parameter. We can now write functions that work for specialized types and that takes in account their type hierarchy and for specialized cases represented with numerical constants.

If you want to do fancier things, you are stuck! Your only way to achieve the result you expect is to write custom branching yourself. This is where Full dispatch comes in action.

Full Dispatch

Full Dispatch instead of redirecting to the right function based on hard-coded parameters such as the type or the equality of the argument with some constant, allows you to provide a function for each argument.

This way, you will be able to dispatch the function based on the criterion you want. You are no more stuck with a special subset of the language.

You would like to write something like this:

int fact(int n : n == 0 || n == 1) { return 1; }
int fact(int n) { return n * fact(n - 1); }

Implementation

To dispatch, we have to know two informations for each overriding method: the actual function and a list of boolean function to test against the parameters.

I’ve chosen to store it as an array of overriding method, where the overriding is stored as an array containing in first element the actual function followed by the argument conditions.

The dispatching function is trivial to write, you just have to walk through that table and if all the arguments match the conditions then call it.

function fullDispatch(arg, list) {
  outer: for (var i = 0; i < list.length; ++i) {
    if (list[i].length - 1 !== arg.length) {
      // Arguments length is different than number of conditions, no need to continue
      continue;
    }
 
    for (var j = 0; j < arg.length; ++j) {
      if (typeof list[i][j + 1] === 'function' && !list[i][j + 1](arg[j])) {
        // Condition fail, try next overriding function
        continue outer;
      }
    }
    // Execute the right function
    return list[i][0].apply(this, arg);
  }
  output.error('no dispatch found');
}

for (var j = 0; j < arg.length; ++j) {
if (typeof list[i][j + 1] === ‘function’ && !list[i][j + 1](arg[j])) {
// Condition fail, try next overriding function
continue outer;
}
}
// Execute the right function
return list[i][0].apply(this, arg);
}
output.error(‘no dispatch found’);
}

And here is the code to use it for the factorial function:

var fact = function () {
  return fullDispatch(arguments, fact.list);
}
 
fact.list = [
  [function (n) { return 1; },
    function (n) { return n === 0 || n === 1; }],
 
  [function (n) { return n * fact(n - 1); },
    null]
];

fact.list = [
[function (n) { return 1; },
function (n) { return n === 0 || n === 1; }],

[function (n) { return n * fact(n – 1); },
null]
];

Helper functions

Most of the time, the condition functions will be trivial to write and will make the code unreadable because of the verbose way to declare an anonymous function.

The first step to make this cleaner was to allow null to be used when you don’t want to impose any condition on the argument. It means “always return yes” and avoid a useless function call.

Then, we want to avoid to write basic conditions such as “is zero” or “is negative”. Using the power of lambda function in association with closure, it’s possible to write generics helpers to make these with no effort.

var helper = {};
 
// Combination
helper.or = function (f, g) { return function (x) { return f(x) || g(x); }; };
helper.and = function (f, g) { return function (x) { return f(x) && g(x); }; };
helper.not = function (f) { return function (x) { return !f(x); }; };
 
// Primitives
helper.Value = function (n) { return function (x) { return x === n; }; };
helper.StrictNegative = function (x) { return x < 0; };
 
// Primitive Combinations
helper.Zero = helper.Value(0);
helper.Negative = helper.or(helper.StrictNegative, helper.Zero);
helper.StrictPositive = helper.not(helper.or(helper.Zero, helper.StrictNegative));
helper.Positive = helper.not(helper.StrictNegative);

// Combination
helper.or = function (f, g) { return function (x) { return f(x) || g(x); }; };
helper.and = function (f, g) { return function (x) { return f(x) && g(x); }; };
helper.not = function (f) { return function (x) { return !f(x); }; };

// Primitives
helper.Value = function (n) { return function (x) { return x === n; }; };
helper.StrictNegative = function (x) { return x < 0; };

// Primitive Combinations
helper.Zero = helper.Value(0);
helper.Negative = helper.or(helper.StrictNegative, helper.Zero);
helper.StrictPositive = helper.not(helper.or(helper.Zero, helper.StrictNegative));
helper.Positive = helper.not(helper.StrictNegative);

Of course, the shown primitive combinations could be written directly but this shows you how to construct and use complex functions based on few bricks.

Final Result

This is an example of the ackermann function written with the Full Dispatch method and the little helper functions.

var ackermann = function () {
  return fullDispatch(arguments, ackermann.list);
}
 
ackermann.list = [
  [function (m, n) { return n + 1; },
    helper.Zero,
    null],
 
  [function (m, n) { return ackermann(m - 1, 1); },
    helper.StrictPositive,
    helper.Zero],
 
  [function (m, n) { return ackermann(m - 1, ackermann(m, n - 1)); },
    helper.StrictPositive,
    helper.StrictPositive]
];

ackermann.list = [
[function (m, n) { return n + 1; },
helper.Zero,
null],

[function (m, n) { return ackermann(m – 1, 1); },
helper.StrictPositive,
helper.Zero],

[function (m, n) { return ackermann(m – 1, ackermann(m, n – 1)); },
helper.StrictPositive,
helper.StrictPositive]
];

Write Less, Do More

The current version works well but is the syntax is too heavy. In order to make this work we have to copy each time the fullDispatch call which isn’t good. We can use a function generator to do the work.

We want to put the conditions first, since they will tend to be smaller, they will appear nicely in one line just before the function definition. And having a setter could be interesting, this would allow to check the input and hide the structure from the user.

Applying these modifications, we would have a code that look like this:

var ack = FullDispatch();
 
ack.add([Zero, null], function (m, n) { return n + 1; });
ack.add([StrictPositive, Zero], function (m, n) { return ack(m - 1, 1); });
ack.add([StrictPositive, StrictPositive], function (m, n) { return ack(m - 1, ack(m, n - 1)); });
ack.add([null, null], function (m, n) { return 0; });

ack.add([Zero, null], function (m, n) { return n + 1; });
ack.add([StrictPositive, Zero], function (m, n) { return ack(m – 1, 1); });
ack.add([StrictPositive, StrictPositive], function (m, n) { return ack(m – 1, ack(m, n – 1)); });
ack.add([null, null], function (m, n) { return 0; });

Which is a pretty nice result. This is not as short as the haskell code but this doesn’t use any syntaxic sugar from the language and can be used with any kind of argument conditions.

ackermann 0 n = n+1 
ackermann (m+1) 0 = ackermann m 1
ackermann (m+1) (n+1) = ackermann m (ackermann (m+1) n)
ackermann _ _ = 0

To make this work we create a function that is going to to the real dispatch and augment it with the setter and the function list.

var FullDispatch = function () {
  // Create the function that does the real dispatch
  var object = function () {
    return fullDispatch(arguments, object.list);
  };
 
  // Give the setter to the function
  object.add = function (conds, func) {
    object.list.push([func].concat(conds))
  }
 
  // Initialize the function list
  object.list = [];
 
  return object;
};

// Give the setter to the function
object.add = function (conds, func) {
object.list.push([func].concat(conds))
}

// Initialize the function list
object.list = [];

return object;
};

Demo

The code demonstrated here can been seen working in a demo.

Follow-Up

This little library is working well as it is. There is still some work to do in this field. First, we have to find uses for this pattern. I haven’t thought yet of any uses of it and the example provided do not show the real benefit of such a tool. I am pretty sure now this is known and implemented some of you will find how to use it!

The second point is performance issues. Having such a modular dispatch system is great for expressiveness but come at a price. The overhead is pretty huge. One dispatch of a call costs at most n * m where n is the number of overriding functions and m is the number of arguments.

Functions can be added a way that only one (or two) conditions are tested each time. By mimicking the way you would write a branching using if-then-else, the overhead is one function call per condition (and per argument).

It’s certainly enough to avoid when performance is required, however I am confident this is acceptable in most conditions compared to the flexibility it gives. Benchmarks would be more than welcome.

CSS – Float Techniques

CSS development is a hard land where you have to struggle with many browser incompatibilities and not so easy to use structures. Here are two extremely useful techniques that allow you to get around common float problems.

List of items without floats

Problem

It is common to display a list of items that flow horizontally. Common examples are tabs or cloud tags. A common way to write it is to use the float property.

<style>
  li { float: left; }
</style>
<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
</ul>

However, you are going to struggle with the way floating elements flow in the document. You have to clear them, you will have strange behaviors with multiple floats …

Technique

There is a better way to do it: display: inline-block;. The element will behave inline (as a span) when being positioned in the flow and as a block when styling it. Exactly what you want.

The code is nearly the same, but the float is now gone!

<style>
  li { display: inline-block; }
</style>
<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
</ul>

However, this code does not work in ie7 (and of course ie6). But … There is a simple trick to make it work! Every time you do a display: inline-block, just add the two associated lines. The magic is explained by Ryan Doherty from Mozilla.

li {
  display: inline-block;
/* The following 2 lines do the magic */
  zoom: 1;
  *display: inline;
}

You can read more about the zoom property and its strangeness on the On Having Layout article.

Benefits

  • No more floats and all the problems involved
  • Cross browser (even ie6)
  • You can now center elements using text-align

Demo

.demo-inline {
text-align: center;
background-color: #ccc;
margin: 0 !important;
padding: 0 !important;
}
.demo-inline li {
display: inline-block;
zoom: 1;
*display: inline;
border: 1px solid red;
margin: 5px;
padding: 5px;
width: 50px;
height: 50px;
}

  • One
  • Two
  • Three
  • Four
  • Five

No more clear to get around floating elements

Problem

When working with floating elements, you are probably going to do something like this:

<div>
  <div style="float: left;">Left Menu</div>
  <div style="float: left;">Another Menu</div>
  <div style="float: right;">Content</div>
  <br style="clear: both;" />
</div>

The problem is you have to use a <br /> which takes vertical space, completely destroy your padding/margin organization …

Technique

There is one easy technique described by PPK that is solving all the problems and has no side effect!

<div style="width: 100%; overflow: auto;">
  <div style="float: left;">Left Menu</div>
  <div style="float: left;">Another Menu</div>
  <div style="float: right;">Content</div>
</div>

The trick is to add width: 100%; overflow: auto; to the parent box and it just works! The parent box now wraps around all the floating elements and you can properly style it. It works will all browsers, even with ie6.

Demo