My JavaScript book is out! Don't miss the opportunity to upgrade your beginner or average dev skills.

Wednesday, December 24, 2008

External selectors as engines and how to create your own library

With "Sizzle event", the challenge about libraries will move from the coolest/fastest selector engine into the coolest/fastest way to use it for library purpose.

Since Sizzle will be just one of them, thanks to our natural behavior ( read: re-create the wheel ) it is possible that there will be more selector engines around the net.

So, why we could not create our own library that does just what we need and nothing else, maintaining a decent size and performing like a jaguar :D ???

Here a truly basic example about how to create your own library, basing it over a generic selector engine or generic library (or just its engine, if you prefer one)

// our wonderful library constructor
function myQuery(){
// just in case we prefer another name for the constructor
// this code is "name proof"
var callee = arguments.callee;
return this instanceof callee ?
this :
callee.prototype.init.apply(new callee, arguments)
;
};

// add some native prototype to created array like instances
// a common pattern for DOM based libraries
with(Array.prototype)
myQuery.prototype = {
constructor:myQuery,
length:0,
pop:pop,
push:push,
shift:shift,
slice:slice,
sort:sort,
splice:splice,
unshift:unshift
};

// add "not standard yet array prototypes", if necessary, or our own cool proottypes
myQuery.prototype.forEach = Array.prototype.forEach || function(Function, self){
for(var i = 0, length = this.length; i < length; i++)
(i in this) && Function.call(self, this[i], i, this);
};

// define the init prototype to use the pre defined engine
myQuery.prototype.init = function(){
var self = this.engine.apply(null, arguments);
this.push.apply(this, self instanceof Array ? self : this.slice.call(self, 0));
return this;
};

// define the engine for this library
myQuery.prototype.engine = Sizzle; // or jQuery

onload = function(){

// enjoy your lib
myQuery(".foo .bar").forEach(function(HTMLElement){
HTMLElement.innerHTML = "Hello Lib!";
});

};


Summary


The main limit is the engine itself, or better, arguments that the engin could accept.
If we change engine and this accepts different arguments or same arguments in a different way, we need to change every call to our library but at least everything else will work without problems.
For this reason it is reasonble to choose a common engine arguments model, like Sizzle, for example, presuming other engine will accept the same list of options and will produce an array like result.
Am I suggesting to avoid famous/common library? Absolutely no, I simply think the selector engine is the most important thing for whatever DOM purpose library :-)

Tuesday, December 23, 2008

Visual Studio 2008 - The good part

... whatever I said in the precedent post, at least VS9 let us extend it and create macros as well.

Unfortunately, I could not create a macro in C# so I had to use a language that I do not like at all, Visual Basic, and the result is an alpha macro that allows us to create "more clever" regions and outline for brackets as well.

More clever regions


There is another macro that goes around since Visual Studio 2005 but it has some bug and/or problem with nested regions plus it does not allow us to write directly in the region what the region is about

//#region whatever
...
//#endregion

--- to obtain
//#region whatever[...]

--- instead of
// another "boring" comment over the region
[...]

At the same time that macro put every region, nested or not, at the beginning of the line. It is not such a big problem, but I prefer this version.


Brackets outline


This is absolutely experimental and there are hundreds of problems, but for a couple of files it is doing its job.


What's next


Christmas, holidays, relax, if it is possible, and a better parser (a char by char via VB, I cannot even imagine me doing it!!!) so be patience please, and enjoy this alpha release :)

' JavaScript macro for bits and bops alpha version
' by Andrea Giammarchi - WebReflection.blogspot.com

Option Strict Off
Option Explicit Off
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports System.Diagnostics
Imports System.Collections

Public Module JSMacros

Sub OutlineBrackets()
Outline("Brackets")
End Sub

Sub OutlineRegions()
Outline("Regions")
End Sub

Private Function Outline(ByVal what As String)
Dim REGION_START As String = "//#region"
Dim REGION_END As String = "//#endregion"
If what = "Brackets" Then
REGION_START = "{"
REGION_END = "}"
ElseIf what = "Regions" Then
REGION_START = "//#region"
REGION_END = "//#endregion"
End If
Dim selection As EnvDTE.TextSelection = DTE.ActiveDocument.Selection
Dim selections As ArrayList = New ArrayList
Dim regions As Stack
Dim current As Stack
Dim endIndex As Integer
Dim startIndex As Integer
Dim text As String
selection.StartOfDocument()
selection.SelectAll()
text = selection.Text
If text.Chars(text.Length - 1) <> vbCr Then
selection.EndOfDocument()
selection.Insert(vbCr)
text += vbCr
End If
regions = FindRegions(text, REGION_START, REGION_END)
If what = "Brackets" Then
OutlineBracketsLoop(REGION_START, REGION_END, regions, selections, text, 0, 0, 0, regions.Count(), New Stack)
ElseIf what = "Regions" Then
OutlineRegionsLoop(REGION_START, REGION_END, regions, selections, text, 0, 0, 0, regions.Count(), New Stack)
End If
SetOutline(selection, selections)
selection.StartOfDocument()
End Function

Private Function CalcLineNumber(ByRef text As String, ByVal i As Integer)
Dim lineNumber As Integer = 1
While 0 < i
i -= 1
If text.Chars(i) = vbCr Then
lineNumber += 1
End If
End While
Return lineNumber
End Function

Private Function FindPosition(ByRef text As String, ByVal i As Integer)
Dim position As Integer = 0
While 0 < i
i -= 1
position += 1
If i = 0 Or text.Chars(i) = vbCr Then
Exit While
End If
End While
Return position
End Function

Private Function FindRegions(ByRef text As String, ByRef REGION_START As String, ByRef REGION_END As String)
Dim result As Stack = New Stack()
Dim pos As Stack = New Stack(2)
Dim startIndex As Integer = 0
Dim endIndex As Integer
Dim index As Integer = 0
Dim subValue As String = ""
Do
startIndex = text.IndexOf(REGION_START, startIndex)
If startIndex = -1 Then
Exit Do
End If
pos.Push(startIndex)
startIndex = startIndex + REGION_START.Length
index = startIndex
endIndex = text.IndexOf(REGION_END, startIndex)
If endIndex = -1 Then
MsgBox("Endless Region")
Exit Do
End If
Do
index = text.IndexOf(REGION_START, index)
If index = -1 Or endIndex < index Then
pos.Push(endIndex)
result.Push(pos)
pos = New Stack(2)
Exit Do
Else
endIndex = text.IndexOf(REGION_END, endIndex + REGION_END.Length)
index = index + REGION_START.Length
End If
Loop
Loop
Return result
End Function

Private Function OutlineBracketsLoop(ByRef REGION_START As String, ByRef REGION_END As String, ByRef regions As Stack, ByRef selections As ArrayList, ByRef text As String, ByVal startIndex As Integer, ByVal endIndex As Integer, ByVal i As Integer, ByVal length As Integer, ByVal current As Stack)
Dim startLine As Integer
Dim endLine As Integer
While i < length
current = regions.Pop
endIndex = current.Pop
startIndex = current.Pop
startLine = CalcLineNumber(text, startIndex)
endLine = CalcLineNumber(text, endIndex)
If startLine < endLine Then
selections.Add(startLine)
selections.Add(FindPosition(text, startIndex) - 1)
selections.Add(endLine)
selections.Add(FindPosition(text, endIndex))
End If
i += 1
End While
End Function

Private Function OutlineRegionsLoop(ByRef REGION_START As String, ByRef REGION_END As String, ByRef regions As Stack, ByRef selections As ArrayList, ByRef text As String, ByVal startIndex As Integer, ByVal endIndex As Integer, ByVal i As Integer, ByVal length As Integer, ByVal current As Stack)
Dim tmpIndex As Integer
While i < length
current = regions.Pop
endIndex = current.Pop
startIndex = current.Pop
tmpIndex = startIndex + REGION_START.Length
selections.Add(CalcLineNumber(text, startIndex))
selections.Add(1 + FindPosition(text, startIndex) + REGION_START.Length + text.Substring(tmpIndex, text.IndexOf(vbCr, startIndex) - tmpIndex).Length)
selections.Add(CalcLineNumber(text, endIndex) + 1)
selections.Add(1)
i += 1
End While
End Function

Private Function SetOutline(ByRef selection As EnvDTE.TextSelection, ByRef selections As ArrayList)
Dim i As Integer = 0
Dim length As Integer = selections.Count()
While i < length
selection.MoveToLineAndOffset(selections.Item(i), selections.Item(i + 1))
selection.MoveToLineAndOffset(selections.Item(i + 2), selections.Item(i + 3), True)
selection.OutlineSection()
i += 4
End While
End Function

End Module

Saturday, December 20, 2008

Visual Studio 2008 and JavaScript: the worst couple ever

We are using Visual Studio 2008 Team Edition at work and it is great for our C# plus SQLServer application, but I am working entirely with JavaScript and every time my files grow up "too much" I start having headache scrolling up and down thousands of line of code.

A basic function that even a small editor like Notepad++ has, the plus/minus sign to close functions closures, does not exists.

You should try to create your own macro, in VB "of course", and call it every time.
As alternative, I added the file extension js in the option with HTML Editor as default editor to let me do something like this

//#region MyConstructor <script>

... my code

//#endregion </stript>

Above start and end comment allows me to close code blocks and everything inside will be highlighted because the editor consider it as an HTML JavaScript tag:
it's true, HTML has open/close blocks while JavaScript does not.

The "fantastic" debugger is nothing that better than the one you can find inside Internet Explorer 8, the only point is that it is integrated with the rest of the project so you can debug both JavaScript and C# at the same time ... without this big effort.

I use FireBug and/or Chrome console indeed, since I do not need to monitor C# that much, and that's it, client side debug feature completely useless under IE ( and I downloaded the version 8 beta 2 yesterday so I can use its debugger instead of launching another local server for client side debug ... )

The intellisense sucks, it does not work automatically as is for C# or other languages or as is for Eclipse or Aptana, you have to put useless syntax in the top of the file to tell the big IDE where are other files.

The suggestion is so clever that if you have a property whose name starts with el, the IDE will autmatically put an else

myObject.else // by the ide


The internal parser does not recognize properly functions as objects, and inheritance is not part of the suggestion ... you should try to disable it if you want to code faster instead of correct IDE suggestions.

In few words, I still wonder why Microsoft is doing everything to discourage the usage of JavaScript and I can't wait to find a valid alternative to integrate my JavaScript projects into source control without being constricted to use the best IDE for C# and the worst ever for JavaScript: Visual Studio 2008

Kind Regards

Wednesday, December 17, 2008

outerHTML for almost every browser ... if you need it ...

We all have to deal with memory leaks problem and apparently a good way to be sure that an HTMLElement has been removed from its "flow" is the outerHTML assignemnt (thanks Ariel for the suggestion)

element.outerHTML = "";
element = null;

If the element is not a document.body or another body parent node, Internet Explorer will "extract" that element from its context, if any, and if there are no other references for that element the null assignment will, theoretically, complete the opera, hopefully solving memory leaks problem for that node as well ...


To remove ... but to replace too ...


Every library has a "swap" or replace method to quickly change an element, but even if we all know that innerHTML is the fastest way to insert content, few libraries use outerHTML to replace nodes, that as far as I know, should be "that fast" in IE as innerHTML is:

// traditional swap, the DOM way
function swap(oldNode, newNode){
var parentNode = oldNode.parentNode;
parentNode.insertBefore(newNode, oldNode);
parentNode.removeChild(oldNode);
};

// spaghetti swap, the outerHTML way
function swap(oldNode, newNode){
oldNode.outerHTML = newNode.outerHTML;
};



outerHTML ... both get and set



try{
HTMLElement.prototype.__defineGetter__.length;
(function(body, removeChild){
HTMLElement.prototype.__defineGetter__(
"outerHTML",
function(){
var self = body.appendChild(this.cloneNode(true)),
outerHTML = body.innerHTML;
body.removeChild(self);
return outerHTML;
}
);
HTMLElement.prototype.__defineSetter__(
"outerHTML",
function(String){
if(!String)
removeChild(this);
else if(this.parentNode){
body.innerHTML = String;
while(body.firstChild)
this.parentNode.insertBefore(body.firstChild, this);
removeChild(this);
body.innerHTML = "";
};
}
);
})(
document.createElement("body"),
function(HTMLElement){if(HTMLElement.parentNode)HTMLElement.parentNode.removeChild(HTMLElement);}
);
}catch(e){};



Conclusion


pro and cons are the same of innerHTML and the reference is lost as is for Internet Explorer, whenever we decide to use this dirty approach to remove or change elements in the DOM. A last example?

function change(strong){
strong.outerHTML = "not strong anymore";
strong = null;
};
onload = function(){
document.body.innerHTML = "click";
};

Saturday, December 06, 2008

A fast and crossbrowser function to make an Array

An absolutely common task present in almost every library, is to transform a generic collection/list of objects or DOM Elements into a friendly Array.

Cases Scenario



  • It is possible to apply directly an Array.prototype.slice call to quickly return an Array

  • It is not possible at all apply every kind of Array prototype to the list



Cases scenario detection


When we execute a piece of JavaScript in a web page, we can assume that we have at least one DOM element in that page, as the script itself for example, so it is always possible to obtain a collection of elements calling document.getElementsByTagName("script") or a generic ("*") in this case probably superflous considering the latter assumption.

Cross browser and fast makeArray proposal



var makeArray = function(push, slice){
try{
// Andrea Giammarchi proposal
slice.call(document.getElementsByTagName("script"), 0);
return function(array, results){
array = array instanceof Array ? array : slice.call(array, 0);
results ? push.apply(results, array) : results = array;
return results
}
}catch(e){
return function(array, results){
if(!(array instanceof Array))
for(var ret = [], i = 0, length = array.length; i < length; i++)
ret[i] = array[i];
else
var ret = array;
results ? push.apply(results, ret) : results = ret;
return results
}
}
}(Array.prototype.push, Array.prototype.slice);


Summary


The try catch is executed only once, the Array prototypes are cached once as well to guarantee cross libraries compatibility. The function is assigned differently for those browsers that can apply the slice prototype to the collection and those that cannot (mainly Internet Explorer).
Accepted parameters are two, inspired by Sizzle function, to allow us to concatenate elements into a collection.

The collection is transformed into an Array only if necessary, since it does not make sense to perform a slice call in every case.

Compatiblity? It should be every browser that supports try and catch statement :-)

Wednesday, December 03, 2008

Stressfull procedure? Distribute your task!

Have you never been in troubles with frozen GIFs or unresponsive HTML?
Sometimes JavaScript could be used to perform really stressful task and a loop, a for in, or an each, could not be fast enough to make your DOM responsive.

What we need in this case is simply a closure to make sure references are consistent and our job will end up in the correct order.

This is a probably silly but I hope interesting function to make the DOM and generally the page more responsive:

Time = {
setTimeout:function(Stack, delay){
var self = this;
if(!delay)
delay = 1;
if(!(Stack instanceof Array))
Stack = [Stack];
setTimeout(function(){
Stack.shift().call(self);
if(0 < Stack.length)
setTimeout(arguments.callee, delay);
}, delay);
}
};

We can call this functon in different ways, stating from the demo:

Time.setTimeout([
function(){
alert("Hello");
},
function(){
alert("Distributed");
},
function(){
alert("Work");
}
]);

untill its more meaningful usage:

var distributed = [];
$("whatever").each(function(i, dom){
distributed.push(function(){
// your stuff to do with i or dom element
});
});
distributed.push(function(){
// your stuff to do after the each call
});
Time.setTimeout(distributed);

Another trick? The usage of the scope injected by each function:

$("whatever").each(function(i, dom){
var self = this;
distributed.push(function(){
return function(){
// your stuff to do with i or dom element
}.call(self);
});
});

Closures against Responsiveness


People expect usability, we expect performances ... at the same time we would like to be able to show a progress, something, that indicate that the page is not completely blocked.

This is a simple way to solve the problem, portable enough, and customizable via closures ... I hope you'll enjoy it :)

Tuesday, November 18, 2008

Ext JS - How to hack the JsonReader

I have a new job ( hooooray?! ) and I suggested Ext JS framework as web UI to focus more about Ajax, XML + XSLT data interactions rather than problems with CSS, events delegations, etc ... and I guess I am doing well, so well, that here I am with a simple tiny trick to hack an Ext.data.JsonReader instance, specially the root and the totalProperty params:

// directly from Ext JS 2.2 API site
// http://extjs.com/deploy/dev/docs/

new Ext.data.JsonReader({
totalProperty: "results", // The property which contains the total dataset size (optional)
root: "rows", // The property which contains an Array of row objects
id: "id" // The property within each row object that provides an ID for the record (optional)
})

Especially for the paginator toolbar, the JsonReader is a must to surf a big amount of data without stressing too much both server and client sides.

One nice feature, or one clever way to make the root node customizable, is the usage of evaluated code via a new Function call.

If the root property ontains a dot, that property is retrieved via nested objec properties.


...
root:"items[0].myList",
...

Thanks to this feature, it is possible to pre parse and pre generate the list that will be assigned as root Array, the one used inside the Grid, DataView, or whatever.Component is managing your interactions.

The trick to pass the returned object to an arbitrary function is this:

...
root:"toString.length||callback(obj)",
...

The callback suppose to be a valid function with a global scope that will return a filtered list of objects compatible with the column model or the data manager we chose.

The trick is based on their regexp that checks simply a dot or a square bracket "[" in the passed string.

That's it, let me discover better tricky stuff in the source and I'll post them :D

Thursday, October 30, 2008

3, 2, ... 1, ... Coming Soon!

Guys, I can't wait for Ubuntu 8.10 and what's up in the website?
The countdown now shows a "Coming Soon" message ... I mean, a little news about when is that difficult?


I know there is a kernel problem since 27 October, and i hope you updated are updating the release to fix that problem with the 8.10 ... but shall you tell us more?
Kind Regards

And thank You :)

Tuesday, October 28, 2008

jQuery plug-in distributed elements via If, ElseIf, and Else

After a couple of instant and consecutive releases, I ended up with a plug-in that fits minified into 240 bytes :)

Here is the official plug-in page, while this is the example page and this is the summary:

;jQuery.fn.extend({
// Andrea Giammarchi - Mit Style Licence - V0.2
If:function(fn){
var __If__ = this.__If__ || this,
$ = __If__.filter(fn);
$.__If__ = __If__.filter(function(){return !~$.index(this)});
return $;
},
Else:function(){
return this.__If__;
},
Do:jQuery.fn.each
}); jQuery.fn.ElseIf = jQuery.fn.If;

Monday, October 27, 2008

jQuery If, ElseIf, and Else plugin

Update
Guys, I have to admit I created silly prototypes while all I need were much more simpler than I though :) Enjoy last version!
-------------------------------------

Try to imagine a page like this one:

<body>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
</body>


.. and now try to imagine something like this:

function oddNumbers(){
// return true if element contain an odd number
return $(this).text() & 1;
};

$(function(){
$("div")
.If(function(){return $(this).text() == "3" || $(this).text() == "5"})
.text("match the 3 or 5 check")
.ElseIf(oddNumbers)
.text("odd numbers")
.ElseIf(function(){return $(this).text() == 2})
.Do(function(){ // if you need a closure ...
$(this).text("text is equal 2");
})
.ElseIf(function(){return $(this).text() == 6})
.text("match the 6 condition")
.Else()
.text("this is 4 or 8");
;
})


... now, try to imagine I created a plugin like this:


;jQuery.fn.extend({
// Andrea Giammarchi - Mit Style Licence - V0.1f
If:function(fn){
var $ = this.filter(fn);
$.__If__ = this.filter(function(){return !~$.index(this)});
return $;
},
ElseIf:function(fn){
var $ = this.__If__.filter(fn);
$.__If__ = this.__If__.filter(function(){return !~$.index(this)});
return $;
},
Else:function(){
return this.__If__;
},
Do:jQuery.fn.each
});


... and now try to enjoy it :D

Kind Regards

Thursday, October 23, 2008

Subclassing JavaScript Native String

Just a quick post about subclassing native String constructor.
All we need is to redefine valueOf and toString methods.

function $String(__value__){
this.length = (this.__value__ = __value__ || "").length;
};
with($String.prototype = new String)
toString = valueOf = function(){return this.__value__};

With incoming V8, TraceMonkey, Squirrelfish, and other (if any ...) advanced engines that transforms repeated code into machine one, performances wont be a problem anymore and everybdy could create its own implementation of the String.

Of course, these statements will be preserved:

var s = new $String("abc");
s instanceof String; // true
s.constructor === String; // true

while typeof will return an object but we can easily use another method such:

$String.prototype.type = function(){
return "string";
};

alert(typeof s); // object
alert(s && s.type()); // string

concat as other native methods willl work, but returned object, unfortunatly, wont be a $String.

Wednesday, October 22, 2008

Big Douglas begetObject revisited recycling a unique function

With the precedent post I realized I wrote a really tricky way to extend inline a function.Next code is the snippet summary:

MyExtendedConstructor.prototype = function(Function){
var callee = arguments.callee;
if(!(this instanceof callee)){
callee.prototype = Function.prototype;
return new callee;
}
}(MyBaseConstructor);

Above code uses the closure itself to create the intermediate constructor.
The reason i chose this way to operate that task was: why should I use another function when I already have one that is the closure itself?

Well done, one function instead of two ... but wait a second, why should I create a different function everytime instead of recycle a single one?

Douglas Crockford begetObject concept


In one of His historical posts, Big Douglas describes simple JavaScript inheritance and object cloning using an intermediate constructor. This is the Object.create function:

Object.create = function (o) {
function F() {}
F.prototype = o;
return new F();
};

Above snippets is still used in I do not know how many JavaScript libraries or code over the net, to extends constructor prototypes or to create a clone of a generic object.

The snippet is clever, powerful, "perfect" for its purpose, but it creates many functions for each object and your JS engine, as your RAM, has not shields to prevent its aggressiveness when you use thousands of times that snippet.

This is a benchmark function example:

function bench(create){
for(var original = {test:"test"}, o = create(original), i = 0, time = new Date; i < 500000; i++)
o = create(o);
return new Date - time;
};

If we test above function with Douglas Object.create one, the result will be something like:

FireFox 3.0.3 - Intel Core2 6600 @ 2.40 - 2GB DDR2 RAM
------------------------------------------------------
Memory: 121.676 Kb
CPU: 50% (not responding)
Elapsed time: 1769 ms



Object.create revisited version


Next snippet is my revisited version of that function:

Object.create = function(Function){
// WebReflection Revision
return function(Object){
Function.prototype = Object;
return new Function;
}}(function(){});

these are advantages about recycling the function:

  • memory should not be increased, the function is one

  • execution speed should be faster, no functions created for each call

  • apparently, not a single behaviour different from the good old snippet


While these are results with the same configuration:

FireFox 3.0.3 - Intel Core2 6600 @ 2.40 - 2GB DDR2 RAM
------------------------------------------------------
Memory: 37.332 Kb
CPU: 35% (responding)
Elapsed time: 855 ms

Seems to be quite impressive, isn't it? Results are tremendously different with Internet Explorer, where the good old way lets the browser ask if it is the case to stop the script: thousands of milliseconds against approximately 1200 with my revision.

Not only to clone


I tested my revision to extend constructors as well, and everything seems to be absolutely fine. This is the function, based on the precedent one:

Function.extend = function(A, B){
A.prototype = Object.create(B.prototype);
A.prototype.constructor = A;
};

// Usage Example
Function.extend(MyExtendedConstructor, MyConstructor);


Why does it work?


Everything is about the clone strategy itself. When we clone an object, it does not matter that the original one is modified, the cloned will be an object a part.
Since the constructor used to create the clone is private, and since it is never modified by the function itself, it does not matter how many times we reassign its prototype, since the only important thing is when we create an instance with new keyword. That instance wont loose its inherited methods or properties.
As example:

function A(){};
A.prototype = {sayHello:function(){alert("Hello")}};
var a = new A;

// prototype redefinition
A.prototype = {};

alert(a instanceof A); // FALSE
a.sayHello(); // Hello

As I said, when variable a is created, it inherits everything from A.prototype and, of course, if A.prototype inherits from another constructor, the chain is respected and classic inheritance emulated. Using the unique function inside that closure, we are doing something like this:

function A(){}; // generic constructor

function Intermediate(){}; // intermediate function
Intermediate.prototype = {sayHello:function(){alert("Hello")}};

// assign the prototype creating an instance
// the instance does not loose its methods
// inherited during its constructor
A.prototype = new Intermediate;

var a = new A;

// we are changing the constructor prototype
// but A.prototype is an instance of the precedent one
Intermediate.prototype = {};

// the method is still there
a.sayHello();

// the prototype has not been changed
// when created it inherited precedent
// methods or variables
var b = new A;
b.sayHello();



Conclusion


In my opinion there aren't side effect but only performances and memory consumption improvements for every browser.
I do not know why I did not think about this way to recycle that function before, but for sure I will never use a new intermediate constructor again, unless somebody will post valid reasons to do it.
Finally, if everybody knew about this tricky way to recycle the constructor, I am sorry, I am late.

a new Relator object plus unshared private variables

This is a Robert Nyman's post dedicated reply, about JavaScript inheritance and alternatives and private variables.

First of all, I would like to say thanks to Robert for both interesting articles He is writing about JS inheritance, and a link to a personal comment which aim was to bring there my "old" documentation about classical JavaScript inheritance and usage of prototype, closures, and public, privileged, or private, scope when we create a constructor.

About


Last Rob's post talk about private variables, describing them as shared, if present outside the constructor, and valid only for singleton instances.
This is true, and could cause a lot of headache if we are not truly understanding closures and prototype shared methods behaviour, but there is a way to use this peculiarity about shared private variables to create dedicated private variables.

Before I will write about it, let's look into a generic shared private variable example:

Click = function(){
// closure for private methods / variables

// private shared variable
var _total = 0;

// returned constructor + prototype
function Click(){};
Click.prototype.add = function(){
_total++;
};
Click.prototype.getTotal = function(){
return _total;
};
return Click
}();

var left = new Click,
right = new Click;

left.add();
alert(right.getTotal()); // 1

Above example shows that if a variable is created outside the constructor and prototype shared methods use that variable, every call to one of those method from a generic instance will modify that single private variable, created once inside that closure. To obtain a private variable we need privileged methods:

Click = function(){ // privileged methods
var _total = 0;
this.add = function(){
_total++;
};
this.getTotal = function(){
return _total;
};
};

var left = new Click,
right = new Click;

left.add();
alert(right.getTotal()); // 0

As discussed before in my doc, in robert's posts, and everywhere else in the web, privileged methods create many functions for each instance, and with big projects this is not good for both memory and CPU usage.

new Relator object and unshared private variables


The Relator is an object capable to relate a generic variable with a clear object, without modifying the original variable.
The classic example is this:

var myNum = 123;
Relator.set(myNum).description = "I am number 123";
alert(myNum.description); // undefined
alert(Relator.get(myNum).description); // "I am number 123"

Since with Relator it is possible to create a unique relation between a generic object and a private Object, it was natural for me to think that a private variable could be a Relator like object using this as unique relationship.
The new version of my Relator still respect the precedent API, being a Relator itself, but is now able to return a new object Relator like that could be used, as example, inside a closure.

// new Relator can create a Relator like object with method "$"
PrivateRelator = function(Relator){
// Relator argument is a new Relator like object
// present only in this scope
return {
get:function(what){
var value = Relator.get(what);
return value && value.value;
},
set:function(what, value){
Relator.set(what).value = value;
}
}
}(Relator.$()); // create a new Relator

Relator.set(window).value = "Hello World";
Relator.get(window).value; // Hello world
PrivateRelator.get(window); // undefined
PrivateRelator.set(window, "Hello Private World");
PrivateRelator.get(window); // Hello Private World
Relator.get(window).value; // Hello World

The good part of Relator is that the stored variable, if it is an object, is stored by reference, and we can assign more than a private unique relationship between a single object and our extra informations.
The same pattern could be easily re-adapted to create a shared private variables:

Person = function(){

// private methods
function _getName(){
return _private.get(this).name
};
function _setName(name){
_private.get(this).name = name;
};

// private variable, shared by every function in this scope
var _private = Relator.$();

// constructor + prototype
function Person(){
// bridge to _private shared variable
_private.set(this);
};
Person.prototype.getName = function(){
return _getName.call(this);
};
Person.prototype.setName = function(name){
_setName.call(this, name);
};
return Person;

}();

// extended constructor
function Enhanced(){
// necessary to save
// this instance into _private variable
// accessible only via Person scope
Person.call(this);
};
(function(){ // quick runtime extend
var callee = arguments.callee;
if(this instanceof callee)return;
callee.prototype = Person.prototype;
Enhanced.prototype = new callee;
})();


var me = new Person(),
rob = new Enhanced();

me.setName("Andrea");
rob.setName("Robert");

alert([me.getName(), rob.getName()]);
// Andrea,Robert


Conclusion


Sometime a limitation could be easily managed to obtain desired result.
In this case, thanks to JavaScript closures and its prototype nature, the shared variable become a sort of bridge to obtain private variables for each instance.
It is important to understand that even if we extend the base constructor, every new instance will still persist into original _private variable, inside the Person scope, unless we do not specify a different one, redefining every method that use that variable as well:

(function(_private){
Enhanced = function(){
_private.set(this);
};
(function(){ // quick runtime extend
var callee = arguments.callee;
if(this instanceof callee)return;
callee.prototype = Person.prototype;
Enhanced.prototype = new callee;
})();
Enhanced.prototype.getName = function(){
return _private.get(this).name
};
Enhanced.prototype.setName = function(name){
_private.get(this).name = name;
};
})(Relator.$());


See you soon ;)

Wednesday, October 08, 2008

JavaScript bits and bops :-)

This post is about a couple of probably useful JavaScript functions, that on daily basis could make our code smarter ;)

String.prototype.Replace


Ok, ok, a prototype into a native constructor is not a good start point, but this one, strings dedicated, is probably one of those "must have" protos, a Replace with multiple inputs, as is for PHP.

String.prototype.Replace = function(replace){return function(RegExp, String){
if(!(RegExp instanceof Array))
RegExp = [RegExp];
if(!(String instanceof Array))
String = [String];
for(var result = this, i = 0, l = 0, index = RegExp.length, length = String.length; i < index; i++)
result = replace.call(result, RegExp[i], String[l < length ? l++ : l - 1]);
return result;
}}(String.prototype.replace);

With above prototype it is possible to search and replace with multiple RegExps and multiple replacements. The proto works as native replace one, but it is possible to perform a replace like this as well:

"abc".Replace([/a/, /b/, /c/], "d"); // ddd
"abc".Replace([/a/, /b/, /c/], ["c", "a", "b"]); // cab
"abc".Replace([/a/, /b/, /c/], ["d", function(){return "e"}]); // dee

Tricky enough?


A meanwhile function pattern


Sometime we need two arguments for a generic callback, but sometime we need to do something between the first argument and the second one.
A common generic example could be a time based callback, where we need to get a start time, to perform an operation, and then an end time.
With a simple pattern like this one:


function meanWhile(before, after){
if(2 < arguments.length)
after = arguments[arguments.length - 1];
// do stuff ... return other stuff
return after - before;
};

We are able to execute a couple of interesting operations.
A timing example is this one:

function bigLoop(){
for(var i = 0, max = arguments[0] || 1000000; i < max; i++);
};
meanWhile(new Date, bigLoop(), new Date); // 180 or less if your PC is faster
meanWhile(new Date, bigLoop(), bigLoop(), new Date); // 360 or less ...

Can you imagine better applications?

P.S. It's long time I do not post guys, sorry but it's really a busy period :)

Wednesday, September 17, 2008

jSmile 0.4 - Stand alone Version

nic comment:
hey. thank u for that awesome plugin. how can i download the smilie package? i want to host them on my webspace because i want to be independet from other hosters.

I have recently updated my jQuery plugin, called jSmile, and the biggest news is that it does not require anymore external resources.

Thanks to inline uri data, the script now comes "full optionals", or better, with base64 encoded GIFs images included.

Instead of external CSS classes, images, and cross host dependencies, jSmile can now easily be integrated in every http or https site, and without network delays.

Its size is obviously bigger than before, but using a minifier and gzip compression, it fits perfectly under 7Kb.

Compatibility



  • Chrome

  • FireFox

  • Internet Explorer 8

  • Opera

  • Safari

  • WebKit



Enjoy ;)

Tuesday, September 09, 2008

Internet Explorer Security Hole - A Better Example

Again, about the security hole I talked about last posts, but this time with a really simple example.

How does the example work



  • Open Internet Explorer, whatever version

  • Go in this page

  • Write a fake user name and a fake password, or a fake email address and a password

  • Click Submit



What does the example do



  • Emulates user actions via javascripts

  • with some version of IE, it could be able to grab both fields values

  • in any case, it demonstrates you that every site could steal your compiled fields in every other site, if the autocomplete option is not forced to be disabled



What could do a malicious, and hidden, code



  • steal your data

  • steal your email

  • steal your credit card information (a really famous company, as example, suffers this problem, so somebody could steal credit cards details of million of people)

  • steal your details

  • steal your searches via common search engines

  • etc, etc



More details in my old post I wrote last Saturday, the one that few people read carefully, understanding what was going on.

This is not a new bug, it exists, and I knew it, since 2004 or before, when banks did not use security checks, yet.

Kind Regards, and please choose another browser until Microsoft will not fix this problem for every IE.

Monday, September 08, 2008

Internet Explorer 6, 7, or 8 exposes users data via JavaScript

Ok, ok, I know these are Google Chrome dedicated days, but how can be possible that my last post did not receive attention at all?

Maybe with this title somebody will read more carefully what I wrote few days ago ... or maybe not, who knows? :?

Thursday, September 04, 2008

Security Basis, and an Internet Explorer data stealer

It has been about 4 years, or more, that I know about this problem, but for some reason I did not talk about it, scared by possible reactions.

In other words, I was waiting for some noise over the net, or some fix from Microsoft, but nothing is happening.

Actually, Microsoft is working hard on Internet Explorer 8, but the problem I am talking about, is still present ... so, I suppose it is time to tell you how dangerous this IE "feature" could be, and how dangerous could be to forget a little detail in a form, like the autocomplete attribute.

The magic autocomplete option


Every browser tries to make our net life as simple as possible, and when we start inserting data in an input field, it suggests us a couple of words or, if the name of that field is unique enough, directly the most probable word, name, or number, we are going to insert.
To perform this operation, we could start typing the name, or simply use the down arrow button to open the list of options, and choose, usually, the first one.

More magic than ever


In some old Internet Explorer versions, like the the 6th one, when we are filling out a login form, we simply need to insert the name, or email, and the password field will be magically populated.
This means that with 3 buttons, 2 down arrows, and 1 enter, we can perform a login.

Magic IE JavaScript


Internet Explorer allows JavaScript developers to fire events simulating user mode.
This means that if we have a focus on an input field, and we fire the keydown event, with down arrow code, the suggested list of options will magically appear.
At the same time, if we repeat the procedure, the first option is highlighted, and if we repeat the procedure again, the second option and so the third one, if any.
More beautiful, is that if we fire the event another time, this time using the enter code, the field will be populated.

How to steal information from the Internet Explorer users


Accordingly, if a malicious website is replicating a form, which user has filled out ones on a genuine website and a dedicated JavaScript starts automatically interacting with the replicated form, the Internet Explorer will silently expose user's information, previously used in "who knows" how many different websites.
A simple, well organized process could try different combinations N times, saving results in an object, or an array, and then sending that information via ajax or a basic get request to a server, allowing the malicious developer to save and reuse that information.

A real world example


To show you what I am talking about, I have created a simplified version of the described script.
Most important things to remember:

  • any displayed information, if any, will not be saved, but only displayed in an alert window, so with my example your data is still your one

  • only Internet Explorer, as far as I know, allows JS developers to create such malicious code to embed in a webpage (that's why I posted about FireFox crash, few days ago :))

  • apparently, IE8, and probably 7 too, do not let developers steal entire login information


To perform this test, you need to use Internet Explorer. If you have never used, or used it only to debug or develop some web applications, please try to login into your favourite web services, for example Gmail.
After that you can directly test my safe example page, and wait few seconds to know if my application was able to get your email account, or whatever else information.

Which websites expose user information?


I am sure this problem is not a secret for Microsoft IE Team, since in every login form, starting from hotmail, they force the atocomplete option to off.
Therefore, it is not possible to steal, for example, hotmail emails, but if you use the same address to login in to another website, which for some reason does not implement the autocomplete off option, it becomes obvious how thousands of spammers can obtain our email addresses in such an easy way.
Gmail login service (surprise!) does not implement the autocomplete off option, so if we use Internet Explorer to login into latter service, our Gmail account name could be easily exposed.
The worst case scenario ever, is represented by Credit Card Forms, where if nobody though about this "little security problem", our Account Name, Credit Card, Verification Code, and whatever else private information, could be grabbed by malicious websites, without us noticing it.
Of course, the expiration date is not that simple to retrieve, but what a powerful weapon this IE feature can be to enhance phishing?
Just try to imagine a page, with similar URL, that already contains all information, but misses only the expiration date, requiring user verification.

As Summary


Other browsers probably know about this problem, since nobody lets JavaScript interact with webpages in the real user mode.
The fix I can simply suggest, is to disable the autocomplete option in Internet Explorer or, even better, change the browser to be sure that if we are inputting our details on a website, that information will not be readable from any other website without our authorization.

Have a nice week end :P

Tuesday, September 02, 2008

Google Chrome Fix

Update 2008/09/04
I have created a new version that should be able to recognise the correct Google directory in every supported windows, and not only English version.

Please do not hesitate to tell me if the created link for No Sandbox Option is not creating it properly, thank you.

Google Chrome Fix Multi Language OS
-----------------------

I successfully tested the new browser in my laptop, while today I had some headache at work.

This is the reason I created in few minutes a simple Windows Application that let you choose which option you want to solve crashes during Google Chrome startup:

The application failed to initialize properly (0x00000005). Press Ok to terminate application.


Please note that the registry fix option changes a key that should solve Symantec problems, but it is not clear if this key could change security level for those PC that use Symantec end point protection, or similar softwares.

In every other case, the GUI create a link to launch Chrome without multiple sandbox, and if I am not wrong, it should mean that multi tab will not be multi thread.

Here you can find the project page, where there is a download section and an executable file.

Thanks to AutoIt developers, and ~d-bliss for the icon.

Enjoy :)

Thursday, August 28, 2008

IE8 Beta 2 - inline images, and anything else

With IE8, we finally can "play" with inline images, specially for CSS or other little decorations.

The main limitation is that the length of the data protocol has a maximum fixed length, but even worst is that IE8 apparently introduced the data protocol only for images.

In another scenario,where we would like to use the same technique for other purposes, IE is still the only browser that does not respect standards.

This is an example:

function evalazy(src, callback){
var script = document.createElement("script"),
body = document.documentElement;
if(callback)
script.onload = callback;
script.type = "application/javascript";
script.src = "data:" + script.type + "," + encodeURIComponent(src);
body.removeChild(body.appendChild(script));
};

Above function is able to evaluate valid JavaScript code in an asynchronous way, calling a callback, if any, when evaluation has been completed ( kinda load runtime an external script ).

Since functions like atob and btoa are still not standard, the script is evaluated as url encoded string.
But even using a base64 string, the result does not change, IE does nothing, or it could generates an error, the classic could not complete the operation due to error 800a03e8 if the body is not present, and in some case, it could even crash during next script execution.

evalazy("testMe = 123", function(){
alert(testMe);
});


In this case the problem is JavaScript, but since the data protocol has been only partially implemented, we will not be able to include every other kind of resource that is not an image.

Hoping I am wrong, and hoping they'll make data protocol more "efficient", let's play with IE8 and its new features, really, and generally, appreciated. Thanks IE8 team :)

Thursday, August 21, 2008

How to crash FireFox 3 with 3 lines of code

Hi there, here I am back from holidays :geek:

Before I'll start to write more interesting stuff, here we have 3 lines of JavaScript that could cause problems to our favourite browser, in this case version 3.0.1

I discovered this problem, already part of the bugs report site, trying to emulate keyboards events using the UIEvents interface instead of KeyboardEvents


var e = document.createEvent("UIEvents");
e.initUIEvent("keypress", true, true, this, 1);
document.documentElement.dispatchEvent(e);


Nice one? See you soon ;)

Tuesday, August 05, 2008

Image Protector, a nice waste of time

I've read right now about another, pointless, attempt, to avoid the classic Save Image As from a website.

Guys, we are in 2008, and I hope that everybody knows what can the simple Stamp / Print button can do, when we are simply watching whatever in our screen.

No way, every tot months, somebody "creates" the ultimate version of an Image Protector, usually based on JavaScript, then "startly pointless" because JS could be easily disabled.

Morevore, this times the trickless trick even requires an excellent library as MooTools is.

Well, since I hate disinformations about techniques to make data truly safe, I can tell you that you need 159 characters to remove the protecion, javascript protocol included.

The funny stuff is that basing the same anti protector over MooTools, since this library is required for the amazing protector, you need even less characters to do the same, basing them on a $$("img") call, instead of document.getElementsByTagName.

Being sure that this technique will be probably adopted from people that do not know a single thing about web or security, and do not know how to implement a basic Watermark, I suppose somebody will implement the same trickless trick, so I prefer to show you the extended link that, if saved in your bookemark, will be able to remove the protection whenever you need, and in a click.

This is the code:

javascript:(function(b,r,l){l=b.length;while(0<l--)r.test(b[l].src)&&b[l].parentNode.removeChild(b[l--]);})(document.getElementsByTagName("img"),/blank\.gif$/);


And this is the link:
noMooreProtection

Save into bookmark, drag there, try the example page, one click in the "bookmarked magic guru crack", and sweat dreams, you can still grab images from those sites that do not have a clue about safe contents :D

Sunday, July 27, 2008

Mousetrap in C language

Just for fun, and performances are horribles as well in new C version, performances are great until 5000 cards, so I need to remove some dust from my good old ANSI C book :D

New version, compatible with gcc compiler.
To create and use the executable, gcc Mousetrap.c

Then call the file Mousetrap 5, for example, to obtain 1,3,2,5,4
Works quickly until 5000 results, requires a monster PC for 1000000 Google limit (algo is still not perfect, but this can generate an entire deck, instead of getting only that index, for each index)

#include <stdlib.h>

int *perfectDeck(int cards);

int main(int argc, char **argv){
if(--argc){
*argv++;
int i = 0,
cards = atoi(*argv);
if(cards > 0){
int *result = perfectDeck(cards);
printf("%i", result[i++]);
while(i < cards)
printf(" %i", result[i++]);
free(result);
}
}
return 0;
}

int *perfectDeck(int cards){
int card = cards,
move = 0,
i = 0;
int *deck = (int *)malloc(cards * sizeof(int)),
*result = (int *)malloc(cards * sizeof(int));
while(card--)
deck[card] = card;
while(cards){
move = (card++ % cards--) + 1;
while(move--){
i = deck[0];
memmove(deck, deck + 1, cards * sizeof(int));
deck[cards] = i;
}
result[deck[0]] = card + 1;
deck++;
}
free(deck);
return result;
}



This is the old version, bad practices everywherem and no movements optimizations (ok, ok, I wrote it too fast)

#include <stdlib.h>

typedef struct {
int length;
int *index;
} Array;

Array new_Array(int length);
Array shift(Array deck);
Array perfectDeck(int cards);
void move(Array deck);

Array new_Array(int length){
Array result;
int i = 0,
*stack = malloc(length * sizeof(int));
while(i < length)
stack[i] = i++;
result.length = length;
result.index = stack;
return result;
}

Array shift(Array deck){
Array result = new_Array(deck.length - 1);
int i = 0,
length = result.length,
*dindex = deck.index,
*rindex = result.index;
while(i < length)
rindex[i] = dindex[++i];
free(deck.index);
return result;
}

Array perfectDeck(int cards){
Array deck = new_Array(cards),
result = new_Array(cards);
int i = 0,
count = 0;
while(i < cards){
while(count++ != i)
move(deck);
result.index[deck.index[0]] = count;
deck = shift(deck);
count = 0;
++i;
}
free(deck.index);
return result;
}

void move(Array deck){
int *index = deck.index,
last = index[0],
i = 1,
length = deck.length;
while (i < length)
index[i - 1] = index[i++];
index[i - 1] = last;
}

/*
int main(){
Array result = perfectDeck(5);
printf("%i %i %i %i %i", result.index[0], result.index[1], result.index[2], result.index[3], result.index[4]);
scanf("%s");
free(result.index);
return 0;
}
*/

Google Code Jam: Mousetrap in 4 languages - GAME OVER

First of all, I would like to thank the Google team for Code Jam opportunity, and its organization: AMAZING!

Yesterday I have lost my Round without a single commit.
This time I have not excuses, it was simply my fault.
I did not understand properly first two problems, or better, expected results, but I was sure the reason was my poor English knowledge, and I wouldn't be silly, asking silly questions (some question was silly enough, so, next time, I'll be less shy than this time).

Accordingly, since Code Jam is a challenge, I chose to solve the most difficult problem, the Mousetrap. First of all, because the problem, and the expected result, was so simple to understand, secondly, because it was the best one for points :geek:

Problem Analysis


Ok, we had 2 hours to analyse the problem, to find the best solution, and to commit results, and this time I did not even download the test, because I would like to be sure that my solution was good enough to solve the problem.

Count positions ... no, don't do it, count movements, no, do not count at all!


My first 3 versions of Mousetrap were so tricky, that no one worked as expected :D
After about one hour trying to find the perfect algorithm to know where each card has to be during the game, I realized that I was trying to solve them in a complex way (a sort of home made equation), and without results, instead of simply think exactly what was going on in the deck during the game.
Anyway, I wasn't able to finish the code, specially because my "perfect solution" was trying to destroy my CPU! So, honestly, for my brain and my knowledge, time was not enough to complete that task.

Brainstorming


My approach was simple: create the perfect deck!
Once we have a perfect deck, find positions is something extremely simple, since each number is, at the begin, a deck index itself minus 1 (i.e. 1,2,3,4,5 as indexes: 0,1,2,3,4), so once you have moved each card over indexes, you can find card positions simply using created array.

card = "5"
result[(int)card - 1] = ... moved card.

At this point, we need to create the deck, and nothing else.
The first version was based on movements, and removed cards, to know the position of each card in that index. A sort of tracing, using a simple function like this one:

function movements(card){
return 0 < card ? card + movements(card - 1) : 0;
}

In this way we can know that when we are looking for card N, we have removed N-1 cards beforfe, and moved movments(N-1) time other cards.
This was probably the right direction, but it was exponential, and results completely wrong ... and snce we had 2 hours, I though to change strategy.

The most simple, logical, and expensive solution at all


Try to imagine we have 5 cards, so the deck will be: 1,2,3,4,5
The sequence, during the game, will be this one:

12345 [card = 1, pos 1]
2345 // remove one, and count fr next card
3452 [card = 2, pos 3]
452 // remove one, and count for next card
524 // counting ...
245 [card = 3, pos 2]
45 // remove one ...
54 // counting ...
45 // counting ...
54 [card = 4, pos 5]
4 // counting ...
4 // counting ...
4 // counting ...
4 // counting ...
4 [card = 5, pos 4]

Above operation is exponential as well, but in my mind it was the best one ever to be sure about the result. That is why I started to play the game!

Mousetrap with JavaScript


When I realized that in that simple way the code was truly slim, I though about 2 possibilities: 1 - I am a f#*@in genius, 2 - There is something wrong, it cannot be that simple, I am an idiot!
Once I have created the code:

// JavaScript
function perfectDeck(cards){
for(var
deck = range(cards),
result = range(cards),
count = 0,
i = 0;
i < cards; i++
){
while(count++ !== i)
deck.push(deck.shift()); // move cards
result[deck.shift()] = count;// remove one
count = 0; // start counter again
};
return result;
};

// JavaScript Extra
function range(length){ // return an array with 1:1 index/value integers
for(var i = 0, result = new Array(length); i < length; i++)
result[i] = i;
return result;
};

// example
alert(perfectDeck(5))
// 1,3,2,5,4

I did some test, and I checked results in my minds, and those were expected. Well done?

Mousetrap, PHP implementation


At this point, I need to parse the input file, and to produce an output file.
Since the code was extremely simple, I have though about PHP, to be able to read the input, and produce the output to upload.

function perfectDeck($cards){
for(
$deck = range(0, $cards - 1),
$result = range(0, $cards - 1),
$count = 0,
$i = 0;
$i < $cards; $i++
){
while($count++ !== $i)
array_push($deck, array_shift($deck));
$result[array_shift($deck)] = $count;
$count = 0;
}
return $result;
}

Damn it, literally 1 minute to create my PHP perfectDeck version.
Now, lets do some test to be sure everything is correct ... ok, that's correct.
At this time, I read the problem again, and I realized that I was debugging with 3, 4, 5 or 7 cards, thinking that a deck could not have more than 15 cards (poker addicted!) ... well, things are a bit different, since limits are clear, and we are talking about a maximum of 5000 cards, and for the small input!!! :o

Python version


Since trying to generate the perfect deck with PHP, and 2500 cards, was extremely slow, I though that I could try to use another language, maybe faster, thanks to Psyco module.

from psyco import full
full()

// Python
def perfectDeck(cards):
deck = range(cards)
result = range(cards)
count = 0
i = 0
while i < cards:
while count != i:
deck.append(deck[0])
deck = deck[1:]
count = count + 1
result[deck[0]] = count + 1
deck = deck[1:]
count = 0
i = i + 1
return result

Of course, in this case Psyco cannot help that much, since the most expensive operation is with the deck, and not with math.

Need for speed, C# Mousetrap


As last chance, and since the code was producing expected results, I though about fixed Arrays, without a single scriptish operation.
Instinctively, I opened my visual C# Express Edition, instead of Dev C++ to create a C version ... maybe because it's long time I am not using them, but anyway, I know that using fixed length arrays I should not have speed problems at all.

// C# with fixed lengths
static int[] perfectDeck(int cards){
int[] deck = range(cards),
result = range(cards);
for(int i = 0, count = 0; i < cards; i++){
while (count++ != i)
move(ref deck);
result[deck[0]] = count;
deck = shift(deck);
count = 0;
}
return result;
}

// C# with fixed lengths - Extra
static int[] range(int Length){
int[] result = new int[Length];
for (int i = 0; i < Length; i++)
result[i] = i;
return result;
}

static int[] shift(int[] deck){
int i = 0,
Length = deck.Length - 1;
int[] result = new int[Length];
for (; i < Length; i++)
result[i] = deck[i + 1];
return result;
}

static void move(ref int[] deck){
int last = deck[0],
i = 1,
Length = deck.Length;
while (i < Length)
deck[i - 1] = deck[i++];
deck[i - 1] = last;
}


Good enough? NO WAY, speed is more close to Python than C, so I promised myself that next version of perfectDeck function will be written in C.
At the same time, it will never be enough fast, because big input as these limits:
T = 10, 1 ≤ K ≤ 1000000, 1 ≤ n ≤ 100, 1 ≤ di ≤ K

This means that my code will perform a factorial 1000000 changes, so honestly, the next step, will be to download some code from the competition, and learn which algorithm is the most clever and simple, to perform this task, in my mind, and in my implementation, completely mechanical.

Conclusion


I like challenges, and this one was amazing. I have learned at least these things yesterday, and I hope next year, I'll be more prepared:

  • Code Jam is fantastic!

  • Do not choose the most difficult task only to be in the top 100, but read in every case all of them before you start to write a single line of code

  • Do not use mechanical procedures, but think about efficient algorithms

  • Do not focus in a code, that for more than 2 times produced wrong results, or simply it is too slow, because it means there is something wrong in the logic, or in the algorithm

  • Go back to school, because even if you are a senior programmer, you do not work for the N.A.S.A. and you do not deal, daily, with algebra, math, geometry, and related stuff



If you are still reading, thank you too, I only would like to share my Google Code Experience, and my perfect costly nightmare Mousetrap solution.

Kind Regards

Saturday, July 26, 2008

JXON - A little update loads of documentation

I have updated my lightweight JXON library right now, lightly improving them, and adding a consistent documentation for each method as well.

At this point, the last thing I could do about JXON, is to talk about what exactly is, and what is not at all.


JXON IS


  • An intermediate, well defined, layer between native JavaScript variables, and a generic page content (their representation inside the layout)

  • A fast and cross-browser JS to XML, and vice-versa, parser

  • A human comprehensive way to represent JavaScript Object Notation via XML using a natural, lightweight, and unambiguous, schema, that will make XSL files creation, manipulation, and maintenance, more clear and natural than ever, working over both XPath, and semantic data types nodes with optional keys for object members

  • A simple and crossbrowser global object, with few methods to transform JavaScript raw data into a valid (x)HTML layout page, or portion

  • An advanced, XSLT based, enterprise ready way to represent data in a generic browser, with possibility to re-use thousands of time the same XSL file, or choose which one should be loaded for that browser (device browser indipendent)





JXON is NOT


  • A JSON parser

  • An Ajax library

  • A template Engine


Indeed, JXON aim is to be easily integrated inside your library, or your own code.
You do not necessary need a JSON parser, but every famous client library has one, so you can still perform client / server interactions using that parser, if necessary, and putting JXON between the evaluated result, and the layout.
The load method principal aim is to assign the public xml property that will be the JXON XML node you need to transform. This means that you have no options to change both its syncronous nature, or to use them to send POST parameters, it is NOT Ajax, but you can use every kind of library or code to perform these tasks putting JXON, again, between these interactions and your automatically updated layout portion.
Finally, thanks to JXON, you could focus entirely about data, instead of data plus its layout representation, delegating latter task to one of the most related languages to do that: XSL, a dedicated markup template engine transformer.

JXON - In line JavaScript to XSLT Example Page

P.S. Above link uses an object instead of a regular layout, and of course, even if when you look at that extremely light page (1.24 kB without gzip), Google and generally every kind of search engine, is able to read those information.

Friday, July 25, 2008

JXON - Lossless JavaScript to XML Object Notation convertion

It seems to be the time to talk about JavaScript template engines, and DocumentFragments, so here I am with my last idea: a JavaScript XML Object Notation transformer.

Introduction


There are a lot of ways to interact between the client, and the server, in a W3 friendly way, such Ajax, the classic remote scripting, Comet, and last, but not least, and probably first of all, XML. The latter "protocol" is one of the most flexible, compatible, and cross platform one you can find in the IT sector, in a word: universal.
Over XML we are loaded of different standards to transport every kind of data, which one should be compatible with browsers, parsers, and preferably with JavaScript DOM implementation as well.
One of the main limitations I have spotted about XML to JavaScript and vice-versa conversion, is the data type, usually lost, and the prolixity of JavaScript data representation.

JSON is great, but whtat's up if we destroy its nature?


The JavaScript Object Notation model, aka JSON, has been one of the most revolutionary protocol between the browser and server, thanks to its thin nature: completely non-redundant against the open and close XML tag style, that is able to make client server interactions faster than ever.
At the same time, JSON is not only about data transportation, it is about data, and data type transportation, so every server side language can receive an object, an array, and every string, number, date, or null, nested information, and this is great!
Some project aim, is to use JSON notation to transform common (x)HTML data into a JSON string, making things almost useless for daily applications.
As example, JSONML goal is to transport HTML over JSON, loosing a consistent portion of this protocol nature because of redundant informations between the client and the server (JSON aim is to transport data, and not its representation in the generic document).
Other libraries try to convert XML or (x)HTML to JSON, and vice-versa, using attributes like "@class", that make client side code usability close to zero

var info = eval('({"@class":"my-class-name"})');
info.@class // error!!!
info["@class"] ...

As I said, JSON is great, robably the best one, to transport data, not its representation, so, the point is: do we really need to put all those information inside a protocol born to be light and essential?

To loose, or not to loose


A common problem in daily XML to JSON and vice-versa transformation, is the data type. A number, is a number, as an array is an array, but XML data is inevitably stored as a string, so the final result, is that almost every XML to JSON parser maintain XML data representation, but looses original JavaScript object notation. The main purpose of JXON, is to maintain original JavaScript data type, using XML to represent them:

<element>
Boolean = <boolean>true|false</boolean>
Date = <date>YYYY-MM-DDTHH:II:SS</date>
Null = <null/>
Number = <number>N|Z</number>
String = <string>string content</string>
Array = <array><element-list/></array>
Object = <object><element-list key="element-key"/></object>

<element-list> = a list of precedent element

For a better explanation about what I am talking about, next example is a full JXON compatible XML node:

<jxon>
<array>
<object>
<string key="developer">Andrea</string>
<number key="age">30</number>
<array key="sites">
<string>webreflection.blogspot.com</string>
<string>www.devpro.it</string>
</array>
</object>
<object>
<string key="developer">Cristian</string>
<number key="age">24</number>
<array key="sites">
<string>mykenta.blogspot.com</string>
</array>
</object>
</array>
</jxon>

Where everything, could be represented in JavaScript, as a developer list, in this way:
[
{
developer:"Andrea",
age:30,
sites:[
"webreflection.blogspot.com",
"www.devpro.it"
]
},{
developer:"Cristian",
age:24,
sites:[
"mykenta.blogspot.com"
]
}
]

And converted to XML, and vice-versa, with a truly simple, and fast, parser.

JXON transformation? XSLT, of course!


The XSLT language, is (x)HTML dedicated, standard, and supported by a wide range of browsers. XSLT could be based on components, matches and templates for every kind of structure, or could be simply dedicated for a single piece of code.
The main advantage of XSLT, is that an XSL file could be easily cached via browser, or server, but it could be always used in the future, while the only thing that will change will be the data, and not its entire structure representation.
What I mean, if you still wondering them, is that we do not need layout informations inside JSON strings at all, since the only thing that we need, and that could change, is the raw data itself, and nothing else.
JXON goal is to completely separate useful JSON informations, from useless, redundant, pointless, layout informations inside JSON protocol itself, making interactions exremely fast, and XSL files re-usability similar to the same we use daily with CSS, to transport only what we need, and to transform them quickly, and in a W3 recommended way as well.

Not clear enough, yet?


So, as last example, I can directly show you what could be possible to do with JXON, and its cross browser implementation, having a look into this unofficial JXON Example page, where you can directly spot the idea, its implementation, and finally its page source code :geek:

Thursday, July 17, 2008

Google Code Jam, or better, how to feel a 100% idiot !

Update 2


Congratulations! The results of the Google Code Jam 2008 Qualification Round are now official, and we're happy to announce that you have advanced to Round 1

Cheers :D
-----------------------------------------

Update


Guys, I do not know what Google judges will think about him/her, but in my mind, the qualification winner, for Python language, is the user camrdale, currently in position 40 of global score grid.

That code is extremely clear (come on, that is Python, how can be different!), essential, and the logic is probably not the perfect one, but is so linear that you can understand the problem even without reading them.

Well done camrdale, and good luck for the contest :geek:
-----------------------------------------

Guys, honestly, I did not think about that kind of selection only to participate, bloody hell!

First of All, the selection started at 11pm, and since I am an employee, and an hard worker as well, I though: who care? I have 24 hours to partecipate.

This is not true at all, I have discovered only after an entire day of work, programming in front at two monitors, drinking 3 red stuff and having 2 coffee, that the classification, or the total score, is based on both results, and when you commit your result.

But who had time to read the task before? Not me, honestly!

This simply means that USA, and vampires a part, nobody could stay in the top of that list.

I was so newbye in this contest, that the instant I went in the page, after login, I started to read the task, downloading automatically the first example file. no way, bad choice as first step, so first task failed because of time, well done!

After that, I chose the second task.
I truly feel like an idiot because I still have not understand at all what the hell is the correct check to avoid trains conflicts. But I hope i will discover soon them, because I am sure somebody more fresh than me understand perfectly the task, and properly solved them.

The last one is probably the most simple one, logically speaking, but at 10:30PM and after 14 hours spent in front of my PC, I really do not know who I am, how can I remember correct geometry permutations?

One think in my mind: I am an idiot!

So thank you for the opportunity Google team, I am sure next year I will ask a week of holidays to participate in another contest like that.

Kind Regards

Wednesday, July 16, 2008

JavaScript Relator Object, aka unobtrusive informations

Have you never though about add, modify, or remove a generic information from a variable, and without changing variable itself?
This is all about what my last simple creation does.



Relator Object Concept


The main purpose for this object is to associate every kind of information, value, or function, into a generic variable, whatever it is, and without modifying its native state.
To obtain this result, I have used a 1:1 relationship between a stack that will contain every stored variable, and another one that will contain related objects.

Stack = [1, 2, 3];
RelatedObject = [{}, {}, {}];

// add a property
RelatedObject[Stack.indexOf(2)].description = "Number 2";

// remove a property
Stack.splice(0, 1);
RelatedObject.splice(0, 1);

// situation
Stack = [2, 3];
RelatedObject = [{description:"Number 2"}, {}];

Using above strategy we obtain 2 benefits:

  1. The Stack does not cause memory leaks

  2. both Stack and RelatedObject are alway as small, and fast, as possible





Related Object Code



var Relator = function(Array, Object){
// (c) Andrea Giammarchi - Mit Style License
if(!Array.indexOf)
Array.indexOf = function(value){
for(var i = 0, length = Array.length; i < length; i++)
if(Array[i] === value)
return i;
return -1
};
return {
get:function(value){
return Object[Array.indexOf(value)]
},
set:function(value){
var i = Array.indexOf(value);
return ~i ? Object[i] : Object[Array.push(value) - 1] = {}
},
del:function(value){
var i = Array.indexOf(value);
if(~i){
Array.splice(i, 1);
Object.splice(i, 1);
};
return this
}
}
}([], []);

I hope, and I suppose, the 3 methods API talks by itself.
set is used to create a relation, if this does not exists, returning associated object.
get is used only to get a relation or undefined, if this does not exist.
Finally, del, is used to delete the relation, reducing the Array size, and deleting related Object.



Some Example


Try to imagine that we are using a library, but we would be able to add any sort of info about them, or implement something for our purpose.

var jQueryMore = Relator.set(jQuery);
jQueryMore.details = "jQuery library";
jQueryMore.isCompatible = function(){
return window.$ === jQuery;
};

// in every other piece of code ...
if(Relator.get(jQuery).isCompatible())
alert("I am using the " + Relator.get(jQuery).details);
// I am using the jQuery library




Relator Performances


IE a part, since it still does not implement natively the old indexOf Array method, performance to set, access, modify, or delete related informations, are probably the best possible, closes to zero value.
We can test by ourself using 10000 stored relations, and accessing to the last one.

for(var i = 0; i < 10000; i++)
Relator.set("number " + i).description = "The " + i + " number";

time = new Date;
description = Relator.get("number " + 9999).description;
time = new Date - time;
alert([description, time]);




Conclusion


The Relator object is based on our own variables, and it is not a container, a register, or a IOC emulator, at all.
At the same time, to be able to relate an object with a generic variable (undefined included, as example), it needs to store them in the Stack.
This could be a problem for memory leaks, but only if we forget to use the del method, to remove the assigned, and protected, relation between our global scope whatever, and the internal object dedicated relation.
Applications? In my mind, this object could make a lot of stuff simpler than ever, specially in those case where we would like, for example, monitor variables, singleton or global instances, during our script life :)

Saturday, July 12, 2008

An alternative JavaScript development pattern

A common pattern to develop JavaScript libraries is to use different behaviours inside methods, and based on browser, or browser plus its version.
For about 80% of cases, these behaviours are Internet Explorer dedicated.
This approach is good enough, otherwise we could not have a wide variety of libraries to choose, but is this way to develop libraries the best one?

These are some pro concepts:

  • libraries could be usually merged into a single file, so we can add only one script tag, and for every browser

  • libraries maintenance or improvements are focused into one, or more, constructor, function, or method



The expected result is, usually, a method that is capable to understand which browser is running them, and what to do for that specific case.

// common libraries development pattern
function myGorgeusLib(){};
myGorgeusLib.prototype.sayHello = function(){
if(self.attachEvent)
attachEvent("onload", function(){alert("Hello")});
else if(self.addEventListener)
addEventListener("load", function(e){alert("Hello")}, false);
else
onload = function(onload){return onload ?
function(){onload();alert("Hello")} :
function(){alert("Hello")}
}(self.onload);
};

new myGorgeusLib().sayHello();

Is above code clear enough? If a browser implements attachEvent, use them, otherwise if it implements addEventListener, use them, otherwise use manual onload implementation.

If we would like to modify, for some reason, that method, there is only one "place" to do it, the method itself.
At the same time, every time we would like to use that method, the browser has to check 1 or 2 times which case is suited for its engine.

This concept introduces these side effects:

  • every method size is generally increased for every browser, and often only to make some task IE compatible

  • every method speed execution, is generally increased, because of useless, or necessary, checks to perform each time the method is called

  • every change inside every method, could cause side effects for other browsers, so we have to fix 3 to 4 times instead of once, because of possible problems

  • every changed method should be tested into every library supported browser, even if it worked perfectly with every one, IE a part



Lazy, or direct, method assignment


Some library implements lazy prototype assignment, so that method will be the best one, only after the first time we will use them.

// lazy method assignment
function myGorgeusLib(){};
myGorgeusLib.prototype.sayHello = function(){
myGorgeusLib.prototype.sayHello =
self.attachEvent ? function(){
attachEvent("onload", function(){alert("Hello")});
}:(
self.addEventListener ? function(){
addEventListener("load", function(e){alert("Hello")}, false);
}:
function(){
onload = function(onload){return onload ?
function(){onload();alert("Hello")} :
function(){alert("Hello")}
}(self.onload);
}
);
this.sayHello();
};

new myGorgeusLib().sayHello();

Since we could perform that kind of check directly during prototype assignment, in this case, above pattern, is completely useless.
On the other hand, doing lazy or direct dedicated assignment, we are using a better approach because:

  • method is specific for this, or that, browser, so its execution speed will be the fastest possible

  • if we need to fix that method, we can focus only into specific browser version. Accordingly, we do not need to test with every supported browser, every change we made, but only with one, or more, specific version


Code minifier maniacs, could think that in this way, and for each method that requires that strategy, the final size of the library could increase about 30%, and this is, basically, true.
So, at this point, we have the best method ever to perform that specific task, but not the best size. How could we solve this last problem?

An alternative library development pattern


Before I will talk about my proposal, we should focus on a simple, as useful, thing about libraries: modularity
What we do like about this, or that, library, is the possibility to include only what we need, to obtain the final result with smallest possible footprint.
In other words, we chose exactly what we need, and we load or use only them, without useless piece of code that could only increase our page size, with or without cache help.
A lot of libraries use this concept runtime, like Dojo, or directly during library generation, like MooTools.
This way to develop, mantain, and use libraries, is loads of benefits for both developers, and users.
At the same time, and as far as I know, nobody though to port this development pattern, to create each library "portion" a part.
This is an example of what I am talking about:

// alternative library development pattern
function myGorgeusLib(){};
myGorgeusLib.prototype.sayHello = function(){
addEventListener("load", function(e){alert("Hello")}, false);
};

// IE dedicated changes, separated file
myGorgeusLib.prototype.sayHello = function(){
attachEvent("onload", function(){alert("Hello")});
};

// if we would like to support really old browsers too, in a separated file
myGorgeusLib.prototype.sayHello = function(){
onload = function(onload){return onload ?
function(){onload();alert("Hello")} :
function(){alert("Hello")}
}(self.onload);
};


This is a benefits summary, about this proposal:

  • smallest library size ever, thanks to common standard methods used by the library itself (a sort of FireFox, Opera, and Safari dedicated version)

  • modular methods development, with separed files dedicated for one, or more, browser version (IE6, IE7, IE8), thanks to conditional IE standard HTML comments: <!--[if IE 7]><script type="text/javascript" src="library.IE7.js"></script><![endif]-->

  • "future proof", when IE will implement standard DOM or Events methods, and behaviours, we can reduce IE dedicated file size

  • single debug, modular updates. We changes only one, or more, file, instead of recompile, regenerate, redistribute, the entire library file

  • intranet friendly, update only library version for dedicated environment, if it uses only a specific browser


So why shoulld we use JavaScript to define library behaviour, instead of browser itself?
Anyway, this pattern completely brakes practices about script tags in a generic (x)?HTML page. But, at the same time, could be the key to solve a wide number of problems, starting from modern devices with possible memory limits for JavaScript files, up to library execution speed, the best possible, and maintenance, focused in a single browser, or a single browser version.
The best implementation could be a Dojo "progressive library load" style, where the core automatically knows which file should be loaded, depending on browser, or its version.
Finally, these are side effects about this pattern:

  • final and complete library size will be the biggest possible one, but there shouldn't be a case where a browser download every file, redefining N times one or more methods

  • more effort to develop an entire library using this way, if there are a lot of methods that are not compatible with every browser

  • probably something else, that I am not thinking about



Now, after this explanation, would you like to write your impressions? Cheers :)