views:

31

answers:

1

I am curious if this is an okay implementation of the Array.filter() method.

//Array of generic Object instances representing galleries. 
//The images property is empty for the example
var galleries:Array = new Array();

galleries[0] = {name: 'Portraits', images: new Array()};
galleries[1] = {name: 'Landscapes', images: new Array()};
galleries[2] = {name: 'Still Lifes', images: new Array()};

//Returns a gallery Object by the specified name
function getGallery(galleryName:String):Object
{
    function isGallery(element:*, index:int, arr:Array):Object 
    { 
        return (element.name == galleryName); 
    }

    var arr:Array = galleries.filter(isGallery);
    return arr[0];
}

var gallery:Object = getGallery('Landscapes');
if(gallery != null)
{
    trace(gallery.name);
}
else
{
    trace('Not found.');
}

This was the function I was using previously:

function getGallery(galleryName:String):Object
{
  for each(var gallery:Object in galleries)
  {
    if(galleryName == gallery.name)
    {
      return gallery;
    }
  }
  return null;
}

I was not able to figure out an implementation of the callback function for the filter() method, where the callback was outside of the getGallery() function. I wonder if there is a way to get the isGallery function outside of the getGallery scope?

+1  A: 

I am curious if this is an okay implementation of the Array.filter() method.

Not only your code is correct, it is a perfect example. for Array.filter usage.

I was not able to figure out an implementation of the callback function for the filter() method, where the callback was outside of the getGallery() function.

It can be, but that beats the point - the idea of those callback functions is to be used mostly as anonymous functions, such as:

//Returns a gallery Object by the specified name
function getGallery(galleryName:String):Object
{
    return galleries.filter(function(gallery:*, idx:int, a:Array):Boolean { 
        return (gallery.name == galleryName); 
    }).shift();
}

Notice the compact code.

I wonder if there is a way to get the isGallery function outside of the getGallery scope?

It's not possible directly, but it is possible if you make it a static function in the parent class, but why do so? See the above code example, it's so compact and reusable by itself.


As a side note, I would replace the whole galleries with:

var galleries:Object = {
    'Portraits': [],
    'Landscapes': [],
    'Still Lifes': []
};

So your 'getGallery' method becomes a O(1) operation:

galleries[name]
LiraNuna
@LiraNuna - This was immensely helpful. The compact aspect of the anonymous function makes sense now. Also, your recommendation to make galleries an Object was brilliant. Thanks!
letseatfood
Glad to help :)
LiraNuna