brainstorming and questions, questions, questions ... really interesting event but now I'm a bit confused :D
Stay tuned on official wiki!
behind the design
My JavaScript book is out!
Don't miss the opportunity to upgrade your beginner or average dev skills.
Saturday, March 31, 2007
Wednesday, March 28, 2007
JavaScript Metaprogramming and MetaDOM
I found really interesting Adam McCrea presentation about JavaScript Metaprogramming but I'm not, absolutely, a Prototype fun :P
I thought about another way to show Metaprogramming power and that's why I wrote a simple MetaDOM object.
What can You do with MetaDOM?
Nothing that You can't do with every JavaScript library, get elements, modify them ... but with this object You should use a sintax like this one:
Semmes cool? This is the example page, tested only with FireFox (and probably this alpha joke version works only with FireFox).
Do You understand better Metaprogramming and do you like it? :D
I thought about another way to show Metaprogramming power and that's why I wrote a simple MetaDOM object.
What can You do with MetaDOM?
Nothing that You can't do with every JavaScript library, get elements, modify them ... but with this object You should use a sintax like this one:
with(MetaDOM){
While("p").Do(AddPNumber);
For("li").In("ul").Do(AddLiNumber);
If("div").class("some-div").Then(WriteSomeDiv);
If("*").class("paragraph").
Then(WriteSomeDiv).
ElseIf("*").id("paragraph").
Then(WriteSomeParagraphId)
;
With("body").Do(function(body){
body.innerHTML = 'MetaDOM Experiment
' + body.innerHTML;
});
If("*").name("h2").Then(AddH3);
};
Semmes cool? This is the example page, tested only with FireFox (and probably this alpha joke version works only with FireFox).
Do You understand better Metaprogramming and do you like it? :D
Friday, March 23, 2007
JavaScript constructor (did you know?)
Update! [2007/03/27]
to know if a generic object is cracked we don't need to create a new instance of its constructor. The fastest, safest and correct way is just to know if this object is an instance of its constructor.
Just fixed the Constructor function ;)
I'm absolutely a JavaScript noob!
Just today I "discovered" that a generic object constructor is not a read-only parameter and I based a lot of conversions with constructor parameter!
What a news for me, I can't believe that every kind of object, except for primitive vairables such String, Boolean and Number, could be modified in this way:
What does it mean?
This means that my PHP_Serializer object, used from a lot of developers, and my byteson library, with its JSON parser, are not so safe to use as I believed.
Malicius code should not be a problem but these objects should fail conversion in a really simple way because they rely on variables constructor.
What about a solution?
The first point is that to change a variable constructor is absolutely the worst JavaScript practice I can think on but we write code and we want a secure one so this is my proposal:
This function returns a generic variable constructor, null or undefined if variable is null, is exactely undefined or if it has an unknown constructor.
That's true, if You change a constructor of a generic object is really difficult to know wich one was changed so this function guarantees, at least, that if returned value is undefined but value is defined, it was "cracked" changing constructor value and in this case, it should be deleted or discarded (IMHO).
This is a simple test case:
Well, now you have a function to check constructors status so right now you can forget a totally nonsense practice as changing constructor is.
That's all folks :)
to know if a generic object is cracked we don't need to create a new instance of its constructor. The fastest, safest and correct way is just to know if this object is an instance of its constructor.
return o instanceof o.constructor ? o.constructor : undefined;
Just fixed the Constructor function ;)
I'm absolutely a JavaScript noob!
Just today I "discovered" that a generic object constructor is not a read-only parameter and I based a lot of conversions with constructor parameter!
What a news for me, I can't believe that every kind of object, except for primitive vairables such String, Boolean and Number, could be modified in this way:
function MyObj(){};
var obj = new MyObj,
str = new String("test"),
sts = "test";
obj.constructor = Array;
str.constructor = Array;
sts.constructor = Array;
alert([
obj.constructor === Array,
str.constructor === Array,
sts.constructor === Array
]); // true, true, false
What does it mean?
This means that my PHP_Serializer object, used from a lot of developers, and my byteson library, with its JSON parser, are not so safe to use as I believed.
Malicius code should not be a problem but these objects should fail conversion in a really simple way because they rely on variables constructor.
What about a solution?
The first point is that to change a variable constructor is absolutely the worst JavaScript practice I can think on but we write code and we want a secure one so this is my proposal:
function Constructor(o){return o === null ? o : Constructor.$[typeof o](o)};
Constructor.$ = {
"boolean": function(){return Boolean},
"function": function(){return Function},
"number": function(){return Number},
"string": function(){return String},
"object": function(o){
var constructor = o.constructor;
return o instanceof o.constructor ? o.constructor : undefined;
},
"undefined": function(){return undefined}
};
This function returns a generic variable constructor, null or undefined if variable is null, is exactely undefined or if it has an unknown constructor.
That's true, if You change a constructor of a generic object is really difficult to know wich one was changed so this function guarantees, at least, that if returned value is undefined but value is defined, it was "cracked" changing constructor value and in this case, it should be deleted or discarded (IMHO).
This is a simple test case:
function Type(){};
var arr = [1,2,3],
obj = {one:"two"},
bot = new Boolean(1),
bom = false,
fun = new Type,
fum = function(){},
num = 1,
nun = new Number(123),
str = "test",
sts = new String("taste");
arr.constructor = String;
obj.constructor = String;
bot.constructor = String;
bom.constructor = String;
fun.constructor = String;
fum.constructor = String;
num.constructor = String;
nun.constructor = String;
str.constructor = Array;
sts.constructor = Array;
alert([
Constructor(arr),
Constructor(obj),
Constructor(bot),
Constructor(bom),
Constructor(fun),
Constructor(fum),
Constructor(num),
Constructor(nun),
Constructor(str),
Constructor(sts)
].join("\n---\n"));
Well, now you have a function to check constructors status so right now you can forget a totally nonsense practice as changing constructor is.
That's all folks :)
Thursday, March 22, 2007
PHP 5 static keyword feature - Part 2
To explain better what did I mean when I talked about static keyword problems, here is some code examples (same result with different languages)
C# (Console Application)
ActionScript 2.0
JavaScript (!!!)
And finally ... what I was doing with PHP before the feature
C++ should be able to do the same thing using overload as C# example.
Instances will inherit static method too but this will not be a problem.
Probably Java and many other languages can do something like these example ... while with PHP You can't.
I don't know about Python overload and specific problem solution, I think Python will have a solution.
Finally, this limit is efficent and simple way to code ... as PHP 5 developers said ... come on guys, I like very much PHP since version 4, but if You implement something, please, do it correctly!
C# (Console Application)
using System;
namespace ConsoleApplication1{
public class StaticString{
private String str;
public StaticString(String str){
this.str = str;
}
public String getString(){
return str;
}
public void write(){
str += " from instance";
StaticString.write(this);
}
public static void write(StaticString what){
Console.WriteLine(what.getString());
}
}
class Program{
static void Main(string[] args){
StaticString ss = new StaticString("Hello World!");
StaticString.write(ss); // I have a static method to do something
ss.write(); // and an instance method to do something else
Console.ReadLine();
}
}
}
ActionScript 2.0
class StaticString { // StaticString.as
// generic public instance method
public function getString(Void):String {
return str;
}
// generic public class static method (correctly not inherited)
public static function write(what:StaticString):Void {
trace(what.getString());
}
/*
// AS 2.0 doesn't accept methods overload
// ... however, this is not a method overload
// this should be an instance method (not a class method)
public function write(Void):Void {
StaticString.write(this);
}
// */
// You could solve this problem ... how ?
// Using a sort of bug (lol)
public var str:String;
// public constructor
public function StaticString(str:String) {
this.str = str;
// AS 2 "bug"
this["write"] = function(Void):Void{
StaticString.write(this);
}
}
}
/* // Test them!
import StaticString
var ss:StaticString = new StaticString('Hello World!');
StaticString.write(ss);
ss["write"]();
// */
JavaScript (!!!)
function StaticString(str){
this.getString = function(){
return str;
};
this.write = function(){
str += " from instance";
StaticString.write(this);
};
if(!StaticString.write)
StaticString.write = function(StaticString){
alert(StaticString.getString())
};
}(new StaticString);
ss = new StaticString("Hello World!");
StaticString.write(ss);
ss.write();
And finally ... what I was doing with PHP before the feature
class StaticString{
private $str;
public final function __construct($str){
$this->str = $str;
}
public final function __call($method, $values){
switch($method) {
case 'write':
$this->str .= ' from instance';
StaticString::write($this);
break;
}
}
public function getString(){
return $this->str;
}
public static function write(StaticString $what){
echo $what->getString(), '<br />';
}
}
$ss = new StaticString("Hello World!");
StaticString::write($ss);
$ss->write(); // Catchable fatal error:
// Argument 1 passed to StaticString::write() must be an instance of StaticString
// none given (hey PHP, I didn't call static class method !)
C++ should be able to do the same thing using overload as C# example.
Instances will inherit static method too but this will not be a problem.
Probably Java and many other languages can do something like these example ... while with PHP You can't.
I don't know about Python overload and specific problem solution, I think Python will have a solution.
Finally, this limit is efficent and simple way to code ... as PHP 5 developers said ... come on guys, I like very much PHP since version 4, but if You implement something, please, do it correctly!
PHP 5 developers teach us what does static keyword mean (and this is a feature!)
PHP 5 introduced a "new" keyword called static.
You can read here what does this keyword mean when it's applied to one method.
As You can read in documentation page
They put last tiny point inside brackets as it's not a really important point to analize!
As You know, with PHP4 every method should be used as static one.
The difference between PHP 4 and PHP 5 seems to be this one:
Well ... static method cannot have a $this reference inside its scope but every static method is inherited into every instance ... this is absolutely hilarious:
To solve PHP 5 static method logic You have to forget static keyword.
The above example shows You how to "solve" static inheritance problems, based on sent arguments (then it's a fake method overload) but shows obviously an E_STRICT notice.
So, at this point, we need a workaround to make a language feature "less buggy and more featurely" ... but static keyword shouldn't be implemented if the diference is only that you can't use instance reference inside one of these method.
This is another example, based on Singleton pattern:
WoW! ... my Singleton instance inherits Singleton pattern, it's amazing!
Obviously, C# and other program languages doesn't assign static class methods into instances ... and the reason is:
To code efficient, easy to mantain I need a clear Object Oriented logic ... and if You're thinking about C++ there's a little difference ...
C++ instances inherit static methods and static parameters too but the big difference is that if you don't declare a class method as static, You can't use them as static method (and You can't use parameters too).
static method and public (instance) one are two different things (as you know) ... but hey, cellog gives me a fantastic, "pure OO way", example to solve my debug problem
That's not portable, not scalable ... absolutely a bad solution ... but it could be simply solved with this code
And "WoW" again! .. that's what I call OOP!!!
Thank you PHP 5 developers to introduce static methods, I hope PHP 6 will be more Object Oriented and less ambiguous than version 5.
Best regards!
[edit]
This is my bug report ... pardòn, bogus report:
http://bugs.php.net/bug.php?id=40886
You can read here what does this keyword mean when it's applied to one method.
As You can read in documentation page
Declaring class members or methods as static makes them accessible without needing an instantiation of the class. A member declared as static can not be accessed with an instantiated class object (though a static method can).
They put last tiny point inside brackets as it's not a really important point to analize!
As You know, with PHP4 every method should be used as static one.
The difference between PHP 4 and PHP 5 seems to be this one:
The big difference between php 4 and php 5 is that a method declared as "static" does not have $this set. You'll get a fatal error, in fact, if you try to use $this in a static method.
Well ... static method cannot have a $this reference inside its scope but every static method is inherited into every instance ... this is absolutely hilarious:
- You can't call with the same name two different methods (one static, for class and one metod for instances)
- You can't overload manually instance method
- Static methods are inherited while static parameters cannot be used from instances
- You can't use $this reference even if You're calling method from an instance (wow, it's really OO)
To solve PHP 5 static method logic You have to forget static keyword.
class StaticString {
private $content = '';
function __construct($content){
$this->content = $content;
}
// I need different methods, not static one inherited!!!
function write($what = null){
echo func_num_args() === 0 ? $this->content : $what->get(), '
';
}
function get() {
return $this->content;
}
}
StaticString::write(new StaticString('static'));
$test = new StaticString('instance');
$test->write();
The above example shows You how to "solve" static inheritance problems, based on sent arguments (then it's a fake method overload) but shows obviously an E_STRICT notice.
So, at this point, we need a workaround to make a language feature "less buggy and more featurely" ... but static keyword shouldn't be implemented if the diference is only that you can't use instance reference inside one of these method.
This is another example, based on Singleton pattern:
class Singleton {
static private $instance;
static private $init = false;
public final static function instance(){
if(!Singleton::$init) {
Singleton::$instance = new Singleton();
Singleton::$init = true;
}
return Singleton::$instance;
}
}
$test = Singleton::instance();
var_dump($test->instance() === $test);
WoW! ... my Singleton instance inherits Singleton pattern, it's amazing!
Obviously, C# and other program languages doesn't assign static class methods into instances ... and the reason is:
If you are wanting absolutely "perfect" OO, there are plenty of other languages that will provide exactly the straightjacket and punishment you desire. If you want to code efficient, easy to maintain, working programs, use PHP.
To code efficient, easy to mantain I need a clear Object Oriented logic ... and if You're thinking about C++ there's a little difference ...
C++ instances inherit static methods and static parameters too but the big difference is that if you don't declare a class method as static, You can't use them as static method (and You can't use parameters too).
static method and public (instance) one are two different things (as you know) ... but hey, cellog gives me a fantastic, "pure OO way", example to solve my debug problem
class ExampleClass {
public $StaticExample;
public final function __construct(){
// bye bye public *parameter*
$this->StaticExample = create_function('$never', 'return "welcome PHP5
ambiguity";');
}
public final static function StaticExample(){
echo "StaticExample", "<br />";
}
}
$test = new ExampleClass();
ExampleClass::StaticExample();
exit($test->StaticExample());
That's not portable, not scalable ... absolutely a bad solution ... but it could be simply solved with this code
call_user_func_array(get_class($a), 'method', $args);
And "WoW" again! .. that's what I call OOP!!!
Thank you PHP 5 developers to introduce static methods, I hope PHP 6 will be more Object Oriented and less ambiguous than version 5.
Best regards!
[edit]
This is my bug report ... pardòn, bogus report:
http://bugs.php.net/bug.php?id=40886
Tuesday, March 20, 2007
for in loop prototype safe
In many different libraries there should be one or more prototype method for every native JavaScript constructor.
Every time You do a for in loop
You probably need to check object[key].
Add prototype to Object constructor is never a good practices, but for in loop can be used with other native constructors too, as example, Array.
The common way to loop over an array is a loop that uses index integer values but sometime You should need to loop over a generic variable just using a for in loop.
In this case the "randomValue" key is part of loop but You can't know everytime wich library add its Array prototype so this is my simple proposal, the $for function.
With these few lines of code You can perform a for in loop without prototype problems, for example:
Used function is automatically cached by $for one so I think this kind of loop will be fast enought (expecially working with internal scope).
Do You like this prototype safe solution? I hope so :)
Every time You do a for in loop
for(var key in object) ...
You probably need to check object[key].
Add prototype to Object constructor is never a good practices, but for in loop can be used with other native constructors too, as example, Array.
Array.prototype.randomValue = function(){
return this[Math.floor(Math.random() * this.length)];
};
var myArray = [1, 2, 3];
alert(myArray.randomValue()); // 1 or 2 or 3
The common way to loop over an array is a loop that uses index integer values but sometime You should need to loop over a generic variable just using a for in loop.
for(var key in myArray) {
// dostuff
}
In this case the "randomValue" key is part of loop but You can't know everytime wich library add its Array prototype so this is my simple proposal, the $for function.
function $for(obj, callback){
var proto = obj.constructor.prototype,
h = obj.hasOwnProperty, key;
for(key in obj) {
if((h && h.call(obj,key)) || proto[key] !== obj[key])
callback(key, obj[key]);
}
};
With these few lines of code You can perform a for in loop without prototype problems, for example:
var myArray = [1, 2, 3],
total = 0;
$for(myArray, function(key, value){
total += value;
});
alert(total);
Used function is automatically cached by $for one so I think this kind of loop will be fast enought (expecially working with internal scope).
Do You like this prototype safe solution? I hope so :)
Wednesday, March 14, 2007
Ultra Zipped Bitmap - a new (un)probable image standard?
Microsoft is working on a new image format, called HD.
It seems to be better than standard JPEG format but it's not a loosequality format.
I've done some strange and stupid test to find a way to obtain the better quality/size effort for an image, and this is the result: uzb image ... what's that? :D
It's quite a joke but it should be a proposal for FireFox, Opera or other browser plugin (is it ridiculous?)
The original uzb image format is Bitmap, that's a looseless image type but it's an "old" format and generated size is amazing.
But, for example, this is an 885 Kbytes ... how many bytes do You think I removed?
Exactly 829,1 Kbytes for a final result of 55,9 Kbytes!!!
This "incredible" final size was obtained using fantastic LZMA compression Algorithm and this size si even better than every png and, as png format, is looseless!
This is what i think about uzb:
Features
- looseless
- extremely fast decompression
- best quality/size ratio
Problems
- slow encoding
- final client "realtime" unpacked size (cache or ram) is probably too much big
- no alpha channel (as JPEG)
You can test by yourself (only for Windows users) decoding speed unpacking in a folder this zip file.
After that You just need to click twice on decode.bat file.
Isn't Wonderful?
If, for some reason, You loose packed file You can get them directly from this link.
The coolest thing is that You're testing a big image that's not "perfect" for your web site, so think about a generic header image like this one, the BitBox header gif image (11,5 Kb), that should be served in 10,3 Kb or another image like this one (216,45 Kb), that should be served in 115 Kb.
Ok guys, it's only a joke :D and packed size is not alawys better than png but quality is always better than JPG, bye!
It seems to be better than standard JPEG format but it's not a loosequality format.
I've done some strange and stupid test to find a way to obtain the better quality/size effort for an image, and this is the result: uzb image ... what's that? :D
It's quite a joke but it should be a proposal for FireFox, Opera or other browser plugin (is it ridiculous?)
The original uzb image format is Bitmap, that's a looseless image type but it's an "old" format and generated size is amazing.
But, for example, this is an 885 Kbytes ... how many bytes do You think I removed?
Exactly 829,1 Kbytes for a final result of 55,9 Kbytes!!!
This "incredible" final size was obtained using fantastic LZMA compression Algorithm and this size si even better than every png and, as png format, is looseless!
This is what i think about uzb:
Features
- looseless
- extremely fast decompression
- best quality/size ratio
Problems
- slow encoding
- final client "realtime" unpacked size (cache or ram) is probably too much big
- no alpha channel (as JPEG)
You can test by yourself (only for Windows users) decoding speed unpacking in a folder this zip file.
After that You just need to click twice on decode.bat file.
Isn't Wonderful?
If, for some reason, You loose packed file You can get them directly from this link.
The coolest thing is that You're testing a big image that's not "perfect" for your web site, so think about a generic header image like this one, the BitBox header gif image (11,5 Kb), that should be served in 10,3 Kb or another image like this one (216,45 Kb), that should be served in 115 Kb.
Ok guys, it's only a joke :D and packed size is not alawys better than png but quality is always better than JPG, bye!
Tuesday, March 13, 2007
function or var function ? part #2
I did an error talking about difference using function, var function and (function), because as Matteo said in my last post I didn't explain perfeclty the difference from an anonymous function and a simple reference variable.
Here You can view an example, probably better than every word:
So, an anonymous function has some limit, as I said on my old post but if You need a simple, tiny function that you're not using as class, You could declare anonymous function even inside a for loop
but if You need a class or a more complex function I suggest to use the "old classic" way:
That's all, You should remember that first example doesn't work,obviously, on Explorer, try them with other standard compilant browser (FireFox, Opera, Safari, Konqueror ... etc)
Here You can view an example, probably better than every word:
var // temporary scope variable declaration
myfunc // variable name (as function referer)
=
function(){}; // anonymous function
alert(myfunc.name);
// empty string because myfunc
// is a reference of an
// anonymous function
// ---------------------------- //
function // temporary scope function declaration
myotherfunc(){};// "the" myotherfunc function
alert(myotherfunc.name);
// string "myotherfunc" because
// myotherfunc is not a reference
// but exactly a function
So, an anonymous function has some limit, as I said on my old post but if You need a simple, tiny function that you're not using as class, You could declare anonymous function even inside a for loop
for(var f = function(){}, a = [1,2,3], b = a.length; b > 0; b--)
// do stuff
but if You need a class or a more complex function I suggest to use the "old classic" way:
function f(){
// do stuff
}
That's all, You should remember that first example doesn't work,
Unobtrusive Blog Entry Date
I really like this Brainstorms Raves blog CSS based entry date tutorial but I like unobtrusive content and graceful enanchemet too :)
That's why I created a simple example page to show You how to create a better unobtrusive example, using less tags on page and a bit of JavaScript for compatible browsers (I suppose every recent browser should support that code).
You could view directly CSS or JavaScript source code, do You like it?
That's why I created a simple example page to show You how to create a better unobtrusive example, using less tags on page and a bit of JavaScript for compatible browsers (I suppose every recent browser should support that code).
You could view directly CSS or JavaScript source code, do You like it?
Thursday, March 08, 2007
Five (better) Javascript Tools Someone Should Have ...
Sometimes there's a JavaScripter that "teach us" wich function should be on our Top Ten function list.
My first disappointment is that if You use a good library, such jQuery, Dojo, !YUI or MooTools You'll never need these functions because these library probably will have better or more powerful implementation.
However, if You absolutely need a "Top Ten" I think it should be created using best version of each function or prototype (write once and forget them).
Please Read JS manual and Respect Standards
This is a common javascripter error, he probably doesn't know well each official method so he thinks we need its code implementation.
For example the common find Array prototype is, at least in my opinion, a big error because JavaScript 1.5 has its dedicated standard function to do the same thing.
We don't need another prototype to do exactly the same thing of standard function, but if we need a different version we should create a little perfect function, don't You agree with me?
This function works inline too (less spaces) but please remember (always) to check if another library has its own implementation.
This is an OpenAjax "compilant way" to make your code unobtrusive and compatible with other libraries too.
The second standard You should respect is method map and any version I've seen respect correctly standard version.
This is a tiny optimized function that should respect them:
Directly from my ByteFW (Byte Framework) Array normalizer.
So, if we just have some standard method why we should use another not standard version with another name?
In this case a standard compilat browser will work in core (fastest way) while other uncompilant browsers will have, I hope, a method like that so "tomorrow" You'll just delete this function from your Top Ten.
Optimize code and take care about its size
Another example should be a generic formatNumber function, that doesn't require to be complex because it should be just this one:
This function should be more short, more simple and probably more fast than other function You could find over the net ... as, for example, this should be a better and more compact way to know if a variable is an Array and not an Object ...
Wow, "just two checks" ... but it's obvious guy, constructor is there from 5 years or more ...
Make your common function "more realistic"
If You need for example a prototype called htmlEntities why You should create a "specialChar like" proto?
Html Entities should parse every html char and not just ['&', '<', '>'] that aren't all possible htmlentitties.
This is for example a better htmlEntities implementation, or probably a real htmlEntities and not a fake htmlspecialchar ...
Choose correctly your "teacher"
He, he ... it's just a joke and I'm absolutely not a teacher but if You want to learn something about JavaScript, please visit Mozilla Developer Center and after that, read code from good libraries "powered by" good developers (jQuery, Dojo, YUI!, others ....
After that Yuo'll never look for a Top Ten "but it's Top Fifteen or Top Twenty" JavaScript post because You'll be able to create them by yourself.
That's all ;-)
My first disappointment is that if You use a good library, such jQuery, Dojo, !YUI or MooTools You'll never need these functions because these library probably will have better or more powerful implementation.
However, if You absolutely need a "Top Ten" I think it should be created using best version of each function or prototype (write once and forget them).
Please Read JS manual and Respect Standards
This is a common javascripter error, he probably doesn't know well each official method so he thinks we need its code implementation.
For example the common find Array prototype is, at least in my opinion, a big error because JavaScript 1.5 has its dedicated standard function to do the same thing.
We don't need another prototype to do exactly the same thing of standard function, but if we need a different version we should create a little perfect function, don't You agree with me?
Array.prototype.find = function(re){
var result=[],i=this.length;
while(i--) {
if(re&&re.constructor===RegExp&&re.test(this[i]))
result.push(i);
else if(this[i]===re)
result.push(i);
};
return result.length?result.reverse():false;
};
This function works inline too (less spaces) but please remember (always) to check if another library has its own implementation.
if(![].find)Array.prototype.find = function(){
// ...
}
This is an OpenAjax "compilant way" to make your code unobtrusive and compatible with other libraries too.
The second standard You should respect is method map and any version I've seen respect correctly standard version.
This is a tiny optimized function that should respect them:
Array.prototype.map = function(callback){
for(var i=0,j=this.length,result=new Array(j),self=arguments[1],u;i<j;i++){
if(this[i]!==u)result[i]=callback.call(self,this[i],i,this);
};return result
};
Directly from my ByteFW (Byte Framework) Array normalizer.
So, if we just have some standard method why we should use another not standard version with another name?
In this case a standard compilat browser will work in core (fastest way) while other uncompilant browsers will have, I hope, a method like that so "tomorrow" You'll just delete this function from your Top Ten.
Optimize code and take care about its size
Another example should be a generic formatNumber function, that doesn't require to be complex because it should be just this one:
function formatNumber(num, pref){
function r(s){return(''+s).split('').reverse().join('')};
return(pref||'')+r(r(num).replace(/^(\d+\.)?(\d+)$/,function(num,d,i){return d+i.replace(/(\d{3})/g,'$1,').replace(/,$/,'')}));
};
This function should be more short, more simple and probably more fast than other function You could find over the net ... as, for example, this should be a better and more compact way to know if a variable is an Array and not an Object ...
function isArray(testObject){return testObject&&testObject.constructor===Array};
Wow, "just two checks" ... but it's obvious guy, constructor is there from 5 years or more ...
Make your common function "more realistic"
If You need for example a prototype called htmlEntities why You should create a "specialChar like" proto?
Html Entities should parse every html char and not just ['&', '<', '>'] that aren't all possible htmlentitties.
This is for example a better htmlEntities implementation, or probably a real htmlEntities and not a fake htmlspecialchar ...
String.prototype.htmlEntities = function(){
return this.replace(/[^\x09\x0A\x0D\x20-\x7F]|[\x21-\x2F]|[\x3A-\x40]|[\x5B-\x60]/g,function(e){return ''+e.charCodeAt(0)+';'});
};
Choose correctly your "teacher"
He, he ... it's just a joke and I'm absolutely not a teacher but if You want to learn something about JavaScript, please visit Mozilla Developer Center and after that, read code from good libraries "powered by" good developers (jQuery, Dojo, YUI!, others ....
After that Yuo'll never look for a Top Ten "but it's Top Fifteen or Top Twenty" JavaScript post because You'll be able to create them by yourself.
That's all ;-)
Tuesday, March 06, 2007
Working on Byte Framework ...
Byte What?
He he :-)
.... I'm working on a framework that will include every interesting personal experiment such bytefx, byteson, bytedom and many others as JSL, Astar for game development, something from JHP, some component, some JS/Canvas/Flash interaction like PixelFont and more and more ... that's why this framework will be probably ready at the end of 2007, at least I hope because as You know, time is never enought.
This post is only a preview of my work in progress and it includes:
... and a work in progress documentation page.
Finally, these are some interesting features about this project:
I hope this project will be interesting but now, I know, it's only a pre alpha release so please stay tuned :-)
He he :-)
.... I'm working on a framework that will include every interesting personal experiment such bytefx, byteson, bytedom and many others as JSL, Astar for game development, something from JHP, some component, some JS/Canvas/Flash interaction like PixelFont and more and more ... that's why this framework will be probably ready at the end of 2007, at least I hope because as You know, time is never enought.
This post is only a preview of my work in progress and it includes:
- a first Tween class demo
- a stupid Css clas demo
- a Bpath (Base Xpath) benchmark against jQuery, Dojo and DOMQuery
- a Bpath compatibility demostration
... and a work in progress documentation page.
Finally, these are some interesting features about this project:
- Compatible with IE 5 or greater
- full compatibility with IE 5.5 or greater
- better FX implementation
- clear source code, parsed and cached directly with my GzOutput class
- cross-browser and quality code for a fast framework
- unobtrusive single namespace, compatible with every other library
- OpenAjax ready
I hope this project will be interesting but now, I know, it's only a pre alpha release so please stay tuned :-)
Monday, March 05, 2007
[IT] Italia - Finalmente i conti tornano - Atto Secondo
Ancora sul portale del turismo?
Assolutamente no, semplicemente una ulteriore riflessione sulle competenze generali in ambito informatico e nello specifico Web di questo bel paese.
Solo oggi scopro la notizia delle Olimpiadi Informatiche e per la prima volta mi ritrovo nel sito dell'evento.
Mentre tutto il mondo parla di Web 2.0 in Italia la situazione è da Web 0.0.1 Alpha.
Se le potenzialità tecniche e teoriche dei cervelli italiani sono riconosciute a livello internazionale come di altissimo livello quelle inerenti la progettazione Web farebbero rabbrividire anche i paesi che si sono affacciati alla New Economy solo da un paio di giorni.
Gli italiani verranno quindi rappresentati alle olimpiadi internazionali dell'informatica con un sito simbolo della nostra assoluta incompetenza.
Metaforicamente parlando è come se alle olimpiadi della matematica si presentasse un team di studenti rappresentati da un sito con scritto in testata una castroneria del tipo:
1 + 2 = 7.914
Questo lo sviluppo tecnologico, questa la realtà dei fatti.
Studenti capaci di disimparare ancora prima di apprendere le basi come vada strutturato un semplice sito, come vada utilizzato un linguaggio di markup, come vadano distribuite o enfatizzate le informazioni, come si possano rendere accessibili dei contenuti, come vada dichiarato un documento, come vadano evitati i frameset, come vada assolutamente "cestinato" un programma discutibile quanto base e mal riuscito come è Front Page per un sito degno di tale nome.
L'italia delle riforme scolastiche e dell'evoluzione Informatica viene rappresentata da quello che è oggettivamente uno dei più discutibili programmi di generazione automatizzata di contenuti che ci siano sul mercato.
Quale novità ? Nessuna, dato che gli sviluppatori del portale del turismo pare abbiano scopiazzato funzioni client prese in rete, eliminandone perfino i copyright, come ulteriore conferma del basso livello di preparazione tecnica, questo il team selezionato per il più ambizioso progetto Web mai finanziato in Italia, non smetterò mai di congratularmi con i governi per l'insieme di assurdità racchiuse in un solo progetto.
Non a caso qualche giorno fa ho scritto un post sul nuovo portale oneweb2.0 rigurado la necessità evidente di riconoscere quella dello scripter una vera e propria professione, probabilmente mi sono sbagliato poichè abbiamo bisogno di molte professioni ufficialmente riconosciute e tecnicamente valide nel settore Web a partire dalla formazione degli stessi docenti della scuola dell'obbligo.
Concludo lasciandovi ammirare il favoloso sito delle Olimpiadi, firmato dal Ministero della Pubblica Istruzione, complimenti ministero!
Assolutamente no, semplicemente una ulteriore riflessione sulle competenze generali in ambito informatico e nello specifico Web di questo bel paese.
Solo oggi scopro la notizia delle Olimpiadi Informatiche e per la prima volta mi ritrovo nel sito dell'evento.
Mentre tutto il mondo parla di Web 2.0 in Italia la situazione è da Web 0.0.1 Alpha.
Se le potenzialità tecniche e teoriche dei cervelli italiani sono riconosciute a livello internazionale come di altissimo livello quelle inerenti la progettazione Web farebbero rabbrividire anche i paesi che si sono affacciati alla New Economy solo da un paio di giorni.
- nessuna dichiarazione del tipo di documento, non sappiamo nemmeno cosa sia il DocType
- utilizzo preistorico di più frame per un sito graficamente discutibile
- utilizzo di applicativi degni di un webmaster al primo giorno di studi (sito realizzato con Microsoft FrontPage 5.0)
- tabelle ed orrori tipici di questi software da principiante amatoriale del Web
Gli italiani verranno quindi rappresentati alle olimpiadi internazionali dell'informatica con un sito simbolo della nostra assoluta incompetenza.
Metaforicamente parlando è come se alle olimpiadi della matematica si presentasse un team di studenti rappresentati da un sito con scritto in testata una castroneria del tipo:
1 + 2 = 7.914
Questo lo sviluppo tecnologico, questa la realtà dei fatti.
Studenti capaci di disimparare ancora prima di apprendere le basi come vada strutturato un semplice sito, come vada utilizzato un linguaggio di markup, come vadano distribuite o enfatizzate le informazioni, come si possano rendere accessibili dei contenuti, come vada dichiarato un documento, come vadano evitati i frameset, come vada assolutamente "cestinato" un programma discutibile quanto base e mal riuscito come è Front Page per un sito degno di tale nome.
L'italia delle riforme scolastiche e dell'evoluzione Informatica viene rappresentata da quello che è oggettivamente uno dei più discutibili programmi di generazione automatizzata di contenuti che ci siano sul mercato.
Quale novità ? Nessuna, dato che gli sviluppatori del portale del turismo pare abbiano scopiazzato funzioni client prese in rete, eliminandone perfino i copyright, come ulteriore conferma del basso livello di preparazione tecnica, questo il team selezionato per il più ambizioso progetto Web mai finanziato in Italia, non smetterò mai di congratularmi con i governi per l'insieme di assurdità racchiuse in un solo progetto.
Non a caso qualche giorno fa ho scritto un post sul nuovo portale oneweb2.0 rigurado la necessità evidente di riconoscere quella dello scripter una vera e propria professione, probabilmente mi sono sbagliato poichè abbiamo bisogno di molte professioni ufficialmente riconosciute e tecnicamente valide nel settore Web a partire dalla formazione degli stessi docenti della scuola dell'obbligo.
Concludo lasciandovi ammirare il favoloso sito delle Olimpiadi, firmato dal Ministero della Pubblica Istruzione, complimenti ministero!
Saturday, March 03, 2007
DOM Google Translator
Hi guys :-)
I've just uploaded my last function on devpro that's compatible with most common browser.
It's based on DOM and creates automatically translation request url to view a selected text or an entire page inside wonderful Google Translator free service page.
Its usage is really simple:
With these example You'll append at the end of document.body a select with LANG - TRANSLATION values and a link.
Returned div has exactly these two elements and You could customize them using your own CSS.
Here You can view another example
In this way You'll create a translator shortcut with default English to Espanol translation.
You can view an example, using English to Italian as default, on the right content of this page, do You like it? :-)
I've just uploaded my last function on devpro that's compatible with most common browser.
It's based on DOM and creates automatically translation request url to view a selected text or an entire page inside wonderful Google Translator free service page.
Its usage is really simple:
onload = function(){
document.body.appendChild(
GoogleTranslator()
);
};
With these example You'll append at the end of document.body a select with LANG - TRANSLATION values and a link.
Returned div has exactly these two elements and You could customize them using your own CSS.
Here You can view another example
<style type="text/css">
#mytranslator {
font-size: 8pt;
font-family: Verdana, Helvetica, sans-serif;
border: 1px solid silver;
padding: 4px;
background-color: #F5F5F5;
color: #000;
width: 160px;
}
#mytranslator select {
font-size: 8pt;
}
#mytranslator a {
display: block;
color: #00F;
text-decoration: none;
border-bottom: 1px dotted black;
}
</style>
<script type="text/javascript">
onload = function(){
var translator = GoogleTranslator(
"Translate",
"es",
"ENG - ESP"
);
document.getElementById("mytranslator").appendChild(translator);
};
</script>
In this way You'll create a translator shortcut with default English to Espanol translation.
You can view an example, using English to Italian as default, on the right content of this page, do You like it? :-)
Friday, March 02, 2007
function, (function) or var function?
Few days ago Dustin Diaz wrote about function declaration ambiguity.
In my opinion the best way to declare a function (class) is the classic way
The reason is simple: a class could be a very big function and some version of Explorer could generate an error if big function is declared using
However this post talks about other function "strange things", expecially about usage of brackets after function declaration.
This will produce an error, exactly a Syntax error.
The "strange thing" is that You could do something inside brackets then function will not be called and syntax error will disappear.
This is a strange "feature" and it's different from this one:
This code will produce a reference error because MyTest, declared inside brackets, has not a global scope then MyTest is correctly undefined.
This is one of the best way to create a lambda function inline too.
As You know len variable will not be a function but a Number with value equal to 3.
The strange thing is that "var" keyword doesn't produce the same result of regular function.
This example will not produce any error and function is called correctly even without arguments.
Next example shows that function works correctly but it's not the value of MyTest variable.
That's why We need to return called function.
Finally You could use these informations to create a real-time interval.
This code will call 10 times the function (20/2 seconds) and not 9.
Do You think this is interesting?
In my opinion the best way to declare a function (class) is the classic way
function MyClass(){
// constructor
};
The reason is simple: a class could be a very big function and some version of Explorer could generate an error if big function is declared using
var MyClass = function (){
// constructor
};
However this post talks about other function "strange things", expecially about usage of brackets after function declaration.
function MyTest(){alert(arguments.length)}();
This will produce an error, exactly a Syntax error.
The "strange thing" is that You could do something inside brackets then function will not be called and syntax error will disappear.
function MyTest(){alert(arguments.length)}
(alert(MyTest));
This is a strange "feature" and it's different from this one:
(function MyTest(){alert(arguments.length)})
(alert(MyTest));
This code will produce a reference error because MyTest, declared inside brackets, has not a global scope then MyTest is correctly undefined.
This is one of the best way to create a lambda function inline too.
var len = (function(){return arguments.length})(1,2,3);
As You know len variable will not be a function but a Number with value equal to 3.
The strange thing is that "var" keyword doesn't produce the same result of regular function.
var MyTest = function(){alert(arguments.length)}();
This example will not produce any error and function is called correctly even without arguments.
Next example shows that function works correctly but it's not the value of MyTest variable.
var MyTest = function(){
alert([arguments.length, arguments[0]])
}(MyTest);
alert(MyTest); // undefined
That's why We need to return called function.
var MyTest = function(){
alert([arguments.length, arguments[0]]);
return arguments.callee
}(MyTest);
MyTest(MyTest);
Finally You could use these informations to create a real-time interval.
onload = function(){
var interval = function(){
document.body.appendChild(document.createTextNode("\n".concat(Math.random() * 1234567)));
return interval ? 0 : setInterval(arguments.callee, arguments[0]);
}(2000);
setTimeout(function(){
clearInterval(interval);
}, 20000);
};
This code will call 10 times the function (20/2 seconds) and not 9.
Do You think this is interesting?
Subscribe to:
Posts (Atom)