SitePoint Sponsor

User Tag List

Results 1 to 1 of 1
  1. #1
    SitePoint Enthusiast
    Join Date
    Feb 2004
    Location
    Third Stone From The Sun
    Posts
    82
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Array.indexOf() should use .equals()

    Array Extra methods indexOf (and lastIndexOf) would be a lot more useful using the equals method (this method does not actually exist yet).

    For those who don't yet know Array Extras
    http://developer.mozilla.org/en/docs...6#Array_extras

    Make indexOf use equals method instead of using ==.

    Code:
    myWrappedString = function(s) {
        this.value = s;
    };
    
    myWrappedString.prototype.equals = function(other) {
        if(!other.value) throw new Error("Unsupported Operation");
        return other.value.toLowerCase().equals(this.value.toLowerCase();
    };
    With the obligatory equals prototype on object.
    Code:
    Object.prototype.equals = function(other) { return this == other; };

    Then you could do stuff like:
    Code:
    var passedValues = userInputValues.filter( caseInsensitiveFilter );

    Anther way would be to allow a comparator...
    Code:
    function caseInsensitiveComparator(x, y) { 
          var a = String(x).toLowerCase(); 
          var b = String(y).toLowerCase(); 
          if (a > b) 
             return 1 
          if (a < b) 
             return -1 
          return 0; 
    }
    
    myStringArray.indexOf( testString, caseInsensitiveComparator);
    I also think that Array.contains() and Array.containsAll() would offer more practical use than indexOf. Any js hacker (even I) could can add these methods to Array and Array.prototype. Native code is better (at least performance-wise).
    Last edited by DHTML Kitchen; Jul 6, 2006 at 14:52. Reason: scrollbar
    My outdated site is down for a while now.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •