Thursday, 30 May 2013


Pairwise an array in Javascript


function pairwise(arr) {
    return arr.map(function (item, index, _arr) {
        return _arr.map(function (_item) {
            if (item != _item) {
                return [item, _item];
            }
        }).filter(Boolean);
    });
}

an example:


pairwise(["Cat","Dog","Bird"]);
# outputs: 
array(3): {
   [0]:  array(2): {
      [0]:  array(2): {
         [0]:  string(3): "Cat"
         [1]:  string(3): "Dog"
      }
      [1]:  array(2): {
         [0]:  string(3): "Cat"
         [1]:  string(4): "Bird"
      }
   }
   [1]:  array(2): {
      [0]:  array(2): {
         [0]:  string(3): "Dog"
         [1]:  string(3): "Cat"
      }
      [1]:  array(2): {
         [0]:  string(3): "Dog"
         [1]:  string(4): "Bird"
      }
   }
   [2]:  array(2): {
      [0]:  array(2): {
         [0]:  string(4): "Bird"
         [1]:  string(3): "Cat"
      }
      [1]:  array(2): {
         [0]:  string(4): "Bird"
         [1]:  string(3): "Dog"
      }
   }
}

Friday, 10 May 2013

The return of preloading images!

Normally I'm not a big fan of preloading images. I feel if your site is well designed, waiting for a few images shouldn't effect the overall user experience.
When and if you do need images preloaded you should just handle them on a case-by-case bases in JavaScript with something like this:

var image = new Image();
image.onload = function() { container.appendChild(image); };
image.src = 'mysrc.png';
Now the user does not have to watch the image load up in the background of your page.
What if you have many images to load for say, a canvas application. This can become very tedious and a lot of code. My solution was just to write a simple ( and small ) preloader that allowed comprehensive callbacks as well as a managed list of images for me to work with. Here is my result:

function preload(list, callback, imageCallback ) {
    var at = len = list.length;
    return list = list.map(function (item) {
        var pItem = new Image();
        pItem.onload = function (i) {
            imageCallback && imageCallback.call(this, this, len-at, len);
            if (!--at) {
                callback(list);
            }
        };
        pItem.src = item;
        return pItem;
    });
}

Example usage:  

var list = preload(["1.png","2.png","3.png" ... ], function complete(list) {
   console.log('images all loaded!');
}, function loaded(image, index, listCount) {
   console.log('image ' + index + ' of + 'listCount is loaded');
});


Download the code here: https://gist.github.com/rlemon/5556905