Faster JavaScript Trim 4

Posted by luca
on Wednesday, May 28

I've recently discovered the very interesting Steven Levithan post about the JavaScript's trim function of the String class.

So, here my version:

function trim13 (str) {
  var ws = /\s/, _start = 0, end = str.length;
  while(ws.test(str.charAt(_start++)));
  while(ws.test(str.charAt(--end)));
  return str.slice(_start - 1, end + 1);
}

More numbers, please!

I tested my function against the benchmarking page of the original post.
Note: times are expressed in MS and are the average of ten executions per browser.
Update [2008-05-29]: I re-runned all the tests and updated results, because Steven noticed that test suite was wrong (few whitespaces).

Mac Windows
Safari 3.1 Firefox 2.0.0.14 Firefox 3.0b5 Opera 9.27 Opera 9.50b2 Internet Explorer 6 Internet Explorer 7 Firefox 2.0.0.14 Opera 9.27 Opera 9.50b2 Average
trim1 25 40 19 100 93 12 12 38 124 111 57
trim2 25 52 29 100 98 6 11 44 125 116 61
trim3 32 54 46 156 148 15 31 57 209 184 93
trim4 43 43 37 151 139 15 38 49 198 186 90
trim5 64 102 104 134 116 65 908 323 291 274 238
trim6 69 115 109 195 171 47 1.497 364 436 338 334
trim7 69 120 107 142 129 31 900 345 330 271 244
trim8 4 118 104 112 97 4 5 540 255 180 142
trim9 34 126 116 1.825 1.218 23 74 113 1.667 1.417 662
trim10 0 1 6 5 3 2 1 0 6 0 2
trim11 2 2 3 11 3 2 2 10 5 7 5
trim12 1 3 2 4 6 1 2 10 4 4 4
trim13 0 0 3 1 1 0 1 2 0 5 1

Please download the benchmark suite, and test against your browsers.

Make your elements draggables and resizeables with Resizeable.js 0

Posted by luca
on Wednesday, March 19

Hello, I'm still alive and I want to share a useful JavaScript class: Resizeable.js. It allows to make draggable and resizeable your DOM elements!

How it works?

new Resizeable('element');

Your element has now two sensible areas: the border area and the central area. If you click on the central area and move the mouse around, keeping the left button pressed, your element will be dragged. If you are on the border area, and perform the same gesture, your element will be resized.

The default size of the border area is 6px, but you can customize it via the options passed to the constructor:

new Resizeable('element', {top:12, right:12, bottom:12, left:12});

Try it now!

Try it now on the demo page.

Credits and License

Resizeable.js is based on Thomas Fakes homonym class and on Thomas Fuchs Scriptaculous, this means it depends on Prototype(1.6.0+) and Scriptaculous (1.8.0+) itself.

Resizeable.js is Free-Software, distributed under the MIT License.

Download

Resizeable.js (md5: aae8256ab0eff3972a03ed67e238e623).

Javascript Alias Method 0

Posted by luca
on Monday, September 03
Working with a dynamic and complete language like Ruby, I feel the lack of many native methods. Lately, I'm working-by-plugin implementing new code, and injecting it into the old one from Rails or Prototype, and so on..

It's a very nice and grateful way of add and remove features on the fly, and change the aspect of the code.

In fact this kind of tecniques and programming paradigms are also called AOP, due to the capability to change the aspect of an object, and, of course, its behaviors.

For this purpose, I feel very useful the Ruby alias_method. Of course, it's a way to create an alias, and eventually override that method, and reuse the brand new name into the old one!!

So playing around a bit with Javascript, I have add this feature to the Object class:
Object.aliasMethod = function(object, newMethodName, oldMethodName) { 
  object[newMethodName] = object[oldMethodName]; 
};


Here a little example:
String.prototype = Object.extend(String.prototype, {
  capitalize: function() {
    return 'The capitalized version of '+this+' is: '+this.aliasedCapitalizeMethod()+'.';
  }
});

alert('fOO'.capitalize());
// -> The capitalized version of fOO is; Foo.


UPDATE
I submitted a patch to the Prototype community and I noticed that the improve to the AOP, was already added into the 1.6.0-rc, by the method wrap. For a complete reference, visit the Sam Stephenson post.

ActiveForm 0

Posted by luca
on Monday, July 23
ActiveForm is a JavaScript library, based on Prototype, useful to validate your forms in an automagically and pluggable way.

Automagically? Simply, You have to declare your fields, eventually your error messages, and.. nothing else!!

Pluggable? ActiveForm contains most common validations (regular expressions, presence, conditional presence..), and it performs them in a certain order. If you don't like this, you can simply redeclare a method, or exclude it from validation process.
ActiveForm performs the validation of a single field following a modular way, executing all methods declared for validation purposes.
This approach makes easy disable, enable, add code portions.
You must simply override a method or declare a new one..

ActiveForm follows Ruby on Rails philosophy: Convention over Configuration and Don't Repeat Yourself.

Here a little example, a login form:
LoginForm = Class.create();
LoginForm.prototype = Object.extend(ActiveForm.prototype, {
  formElement : {id : 'login', event_trigger : 'submit'},
  fields      : {username : {required : true},
                 password : {required : true}}
})


What we have done?
The first line is the class instantiation, second one needs to extend ActiveForm superclass.
The third line is the form element declaration, we specify his id and his validation event.
In the fourth line we declare our fields and we explicit that they are required.

ActiveForm allows forms behavior's inheriterance, following DRY logic.
In your applications, you have similar forms, why write same code for similar pages?
Do you rememeber previous example? if you have a login form (username and password) and a registration form (username, email, password and password confirmation), why not extend first form behavior to the second one, without write a single line of code?
How it works? I've created a Rails like handler: before_create. It allows to extends variables (not override), before class instantiation. Example:
RegistrationForm = Class.create();
RegistrationForm.prototype = Object.extend(LoginForm.prototype, {
  formElement : {id : 'registration', event_trigger : 'submit'}
})
ActiveForm.prototype.before_create(
  Object.extend(LoginForm.prototype.fields,
    fields      : {email                    : {required : true},
                   password_confirmation    : {required : true}}
  )
)


What we have done?
First part of the code needs to declare our subclass, notice we are extending LoginForm (not ActiveForm), because we want inherit its behaviors.
The second part needs to extend fields variable!! When RegistrationForm will be instantiated, fields will had four elements, not two!! Do you like it? Here other features:

  • Prototype based
  • 100% OOP
  • Total/partial inheriterance
  • Non-Obtrusive scripting
  • Validation modulatity
  • Validation customization
  • Blocking/Non-Blocking validation
  • Dynamic visual style customization for each form element
  • Most common regexps already included (you can extend/override them)
  • Most common validation (you can extend/overrider them)
  • Crossbrowser: tested on IE 6+, FF 2+, NS 8+, Op 9+ on Windows XP and Linux (sorry, for Mac people, but i haven't access to a Mac OS X machine)
How much it cost? Nothing!! ActiveForm is Free Software, released under the LGPL License.


Download


ActiveForm 0.2.0 released 0

Posted by luca
on Wednesday, March 28
ActiveForm is a JavaScript library, based on Prototype, useful to validate your forms in an automagically and pluggable way.

Automagically? Simply, You have to declare your fields, eventually your error messages, and.. nothing else!!

Pluggable? ActiveForm contains most common validations (regular expressions, presence, conditional presence..), and it performs them in a certain order. If you don't like this, you can simply redeclare a method, or exclude it from validation process.

Features:

  • Prototype based
  • 100% OOP
  • Total/partial inheriterance
  • Non-Obtrusive scripting
  • Validation modulatity
  • Validation customization
  • Blocking/Non-Blocking validation
  • Dynamic visual style customization for each form element
  • Most common regexps already included (you can extend/override them)
  • Most common validation (you can extend/overrider them)
  • Crossbrowser: tested on IE 6+, FF 2+, NS 8+, Op 9+ on Windows XP and Linux (sorry, for Mac people, but i haven't access to a Mac OS X machine)


ActiveForm is Free Software, released under the LGPL License.

Read more about ActiveForm.

Javascript HashMap 2

Posted by luca
on Monday, October 30

Reading around i've discovered that Javascript associative arrays returns unpredictable results, i.e. length param is not correctly handled.

Array object should be used only with a numeric index and best way to avoid this problem is to use Object.

But, if I wanna put more objects in my object?

Of course i can do this with previous method, but i don't like it :-P. So, i've written a 100% OOP class, that use Prototype and it simulate a java HashMap.

I've also implemented an exception handling.

A little example:

var myHM = new HashMap();
myHM.put('a', new String('This string contains A'));
myHM.put(new String('b'), new String('This string contains B'));
myHM.put('0', new String('And this string? Zero'));
window.alert(myHM.size());  // returns 3

// Replace
// Notice that you can use both String object or scalar value.
myHM.put('b', new Date());
if( myHM.get('b') instanceof Date )
  window.alert('It\'s a Date');
// Remove
if( myHM.containsKey('a') && myHM.containsValue('This string contains A') )
  window.alert('\'A\' object is present');
myHM.remove('a');
if( myHM.containsKey('a') || myHM.containsValue('This string contains A') )
  window.alert('Ooops \'A\' is still present');   // Don't display

window.alert(myHM.size());  // returns 2

// Clear
myHM.clear();
window.alert(myHM.size());  // returns 0

I hope this is useful for you, of course I've attached source code.