Lazy Map FIlter

Overpowered JavaScript function of the day. Demonstrates lazy enumeration.

HTML

<div id="cats"></div>

JavaScript

// Take an array, map it, then filter that result, this is then returned as a function that acts like an enumerable
function LazyMapFilter(array, map, filter) {
    var pos = 0,
        length = array.length;
        
    function next(callback) {
        if (pos < length) {
            var element = array[pos];
            
            pos++;
            
            map(element, function(data) {
                if (filter(data)) {
                    callback(data);
                } else {
                    next(callback);
                }
            });
        }        
    };
    
    return next;
}

// Example, pull a list of images from flickr that are tagged with cat.  Search the list for users that also have an image tagged cute.  Output the first image from said user for each call.

var source = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?&format=json";

function addImage(user) {
    $("<img/>").attr("src", user.items[0].media.m).appendTo("#cats");
}

$.getJSON(source, {tags: "cat", tagmode: "any"}, function(flickr) {
    var list = LazyMapFilter(flickr.items, 
        function(item, callback) {
            $.getJSON(source, {id:item.author_id}, callback);
        }, function(user) {
            return user.items.some(function(item) {
                return item.tags.match(/cute/) != null;
            });
        });
    
    list(addImage);
    list(addImage);
});