16 March, 2006

Numbers versus int values

In javascript, it is very usefull than one can prototype primary classes like String, Array or Date.

Lot's of Ajax Frameworks do it. Prototype for example adds a 'return length;' command to the push Array method so that you can push an element into an array and get the new size in the while.

In Ruby, you have the possibility to call integer methods to tell the script to do something special. For example if you want to do a loop 10 times, you can use the expression 'for 10.times'. You se that the method (or attribute) is attached directly to someting that looks like an integer. It doesn't event seem to be an object.

In Javascript, it's different. You cannot call a method directly from an integer value. But you can do it from an object of class Number.
Take the example of date attributes (day, month, year) that are numbers. You want to display them on the screen within a 2-digit format like this : '03/15/06'
If you call theDate.toString() you get '3/15/2006' because they are numbers.
Let's prototype the class String first and then Number :

//Repeat a string 'many' times
String.prototype.repeat = function(many) {
var s = '', t = this.toString();
while (--many >= 0) s += t;
return s;
}
//Left fill a number with zero so that the result has a length of 'many'
Number.prototype.addZero = function(many) {
return ('0'.repeat(many) + this.toString()).substring(('0'.repeat(many) + this.toString()).length - many);
}

And now you can do :

var i = 5;
i.addZero(10); //You get the string '0000000005'
OR (new Number(5)).addZero(10);
BUT NOT 5.addZero(10);

What is cool is that any integer value return by the javascript primary classes is a real Number and not just an integer. So for dates formatting, you can use the following :

Date.prototype.toFullString = function() {
return this.getDate().addZero(2) + '/' + (this.getMonth()+1).addZero(2) + '/' + this.getFullYear();
}
}

Pretty cool hun ?!

1 comment:

Anonymous said...

You cannot call a method directly from an integer value.

Sure you can:

> (5).addZero(10);