pwnt.be

More JavaScript

Another addition I would like to see in MooTools—or, better yet, ECMAScript in general—is the equivalent of Java’s String.equalsIgnoreCase(String) function. Sure, a first implementation is trivial:

String.extend({
  'equalsIgnoreCase': function(str) {
    return (this.toLowerCase() == str.toLowerCase()
      && this.toUpperCase() == str.toUpperCase());
  }
});

… but if you want it to be a little more efficient, you’ll avoid inspecting both strings in their entirety first and use String.charAt(int) instead. If your motto is ‘Code is Poetry’, you’ll end up with something like …

String.extend({
  'equalsIgnoreCase': function(str) {
    var i = -1;
    if (this.length == str.length) {
      i = 0;
      while (i < this.length
      && this.charAt(i).toLowerCase() == str.charAt(i).toLowerCase()
      && this.charAt(i).toUpperCase() == str.charAt(i).toUpperCase()) {
        i++;
      }
    }
    return (i == this.length);
  }
});

Since ECMAScript is weakly typed and doesn’t have a Character class like Java does, the actual comparison still uses string functions. I wonder how much this influences the algorithm’s performance.

Update: I added the String.toUpperCase() calls, because Java’s implementation has them too. I’m no expert when it comes to international characters.

Post a Comment

This contraption supports Gravatar, as well as Markdown with SmartyPants. If none of that made sense to you, feel free to ignore it and start typing.

  • :)
  • :D
  • ;)
  • :-O
  • :P
  • :@
  • :$
  • :S
  • :(
  • :'(
  • :|
  • :-#
  • 8-|
  • ^o)
  • :-*
  • +o(
  • :^)
  • *-)
  • 8-)
  • |-)
Disorientation
Continuity
Tangentiality
Retributions
Introducing Pwnt.TagSphere
Tim, John Brand
Lplayer for the Rest of Us
Tim, PixelPirate
Pidgin to Adium Emoticon Theme Converter
Tom, Tim, peter
The HTC Desire Kicks the HTC Legend’s Ass
Tom, Tim, Tom, Tim, Tim, Tom
Google Chrome Still Sucks
smeezekitty, Tim, milosh
Colophonics