Prototype's Array.any/all with jQuery

I needed to convert a couple Array.any() and Array.all() calls (from Prototype) to jQuery syntax. Since jQuery doesn't extend the built-in objects with nice functionality like this, you have to fake it. Here's what I came up with. Old version ('images' is an array):

images.all(function(o){return o.status == "ready";})

and the new version:

jQuery.inArray(false,
  jQuery.map(images, function(o){return o.status == "ready";})
) < 0

Array.any()'s equivalent is the reverse:

jQuery.inArray(true,
  jQuery.map(images, function(o){return o.status == "ready";})
) >= 0

Might have to rip the Enumerable and Array extensions out of Prototype for standalone use as well.

10 responses to “Prototype's Array.any/all with jQuery”

  1. Patrick McElhaney

    I found a slightly simpler way to do what you want.

    All:

    jQuery.grep(images, function(o){return o.status == "ready";}).length == images.length

    Any:

    jQuery.grep(images, function(o){return o.status == "ready";}).length > 0

    Also, have you looked at the Collection plugin? I haven't used it myself, but it might have some of the stuff you're missing.

    If I were you I would try and avoid bringing stuff over directly from Prototype. It might stifle your JQuery indoctrination. :-)

  2. Matt W.

    I believe jQuery does it for forward compatibility. See prototype using getElementsByClassName which is now native to Firefox 3.

  3. Matt W.

    I see what you are saying, but my point was that because prototype added the getElementsByClassName method to the document object, it will overwrite the native implementation in Firefox 3. The native implementation should always be significantly faster. If jQuery were add to the grep method to the Array object directly, it would overwrite any future native grep method.

  4. Matt W.

    They did do that, but here is an article that discussed the problems that happened when getElementsByClassName went native –

    http://ejohn.org/blog/getelementsbyclassname-pre-prototype-16/

  5. JDD

    Prototype's addition of document.getElementsByClassName() is deprecated and it is encouraged to use $$() instead.

    They returned the results $A'd to support chaining.
    Prototype created the document.getElementsByClassName function before it was even marked for addition in the effected browsers.

    - JDD

  6. Andy
    (function(window, $, undefined) {
      $.fn.all = function(callback) {
        var all = true;
        this.each(function() {
          if ( !callback.call(this) ) {
            all = false;
            return false;
          }
        });
        return all;
      };
      $.fn.any = function(callback) {
        var any = false;
        this.each(function() {
          if ( !!callback.call(this) ) {
            any = true;
            return false;
          }
        });
        return any;
      };
    })(this, jQuery);