The Usage of UnlimitJS

When writing JavaScript using jQuery,Mootools.. you probably often start with statements like this.

$('input.name').val();

Coming back latter you decide to trim the name, so you add $.trim to the beginning and ) to the end.

$.trim($('input.name').val());

You then decide to split the first name, from the last name and map out any invalid characters.

$.map($.trim($('input.name').val()).split(' '),function(str){
  return str.replace(/[-^&]/,'');
});

Finally you decide to rejoin the first name and last name, and alert the value.

alert($.map($.trim($('input.name').val()).split(' '),function(str){
  return str.replace(/[-^&]/,'');
}).join(' '));

The above is arguable very ugly and unmanageable. It's incredible difficult to tell where one parenthesis ends for a function and another begins. You potentially have to read the entire statement if you intend to ever edit the code.

Solution!

Javascript has a native solution, it's called prototype extension and chaining. Basically you add prototoypes String.prototype.trim = /* implementation */ and you could start writing: ' string '.trim() instead of calling functions like $.trim(' string '). Now although I do agree extending the prototype has its convenience, it also has its very unfortunate side effects including:

  1. Extending an objects prototype messes up for in loops.
  2. If you extend a prototype, you have the potential for your methods to be overwritten, as well as overwriting others

Ultimately, atleast in my personal opinion, prototype extension of native Object s should only should generally be limited to the agreed standard.

UnlimitJS avoids the property overwrite issue, while still allowing chaining.

You can rewrite this

alert($.map($.trim($('input.name').val()).split(' '),function(str){
  return str.replace(/[-^&]/,'');
}).join(' '));

as

$.trim[Unlimit](true);
$.map[Unlimit](true);

alert(
  $('input.name')
  .val()
  [$.trim]()
  .split(' ')
  [$.map](function(str){
    return str.replace(/[-^&]/,'');
  })
  .join(' ')
)

Fork me on GitHub