      1 /**
      2  * @namespace
      3  * @private
      4   */
      5 pockets.collections = {};
      6 /**
      7  * @namespace
      8  * @private
      9  */
     10 pockets.collections.array = {};
     11
     12 /**
     13  * Implementation of Array#eachAsync
     14  *
     15  * @private
     16  * @param collection
     17  * @param doer
     18  * @param onComplete
     19  */
     20 pockets.collections.eachAsync = function(collection, doer, onComplete) {
     21   if (collection.length === 0) {
     22     onComplete();
     23     return;
     24   }
     25   var outstandingRequests = collection.length;
     26   collection.each(function(item) {
     27     doer(item, function() {
     28       if (--outstandingRequests == 0) {
     29         onComplete();
     30       };
     31     });
     32   });
     33 };
     34
     35 /**
     36  * Implementation of Array#collectAsynch
     37  * @private
     38  * @param collection
     39  * @param doer
     40  * @param onComplete
     41  */
     42 pockets.collections.collectAsync = function(collection, doer, onComplete) {
     43   var outstandingRequests = collection.length;
     44   var transformedValues = [];
     45
     46   if (collection.length === 0) {
     47     onComplete(transformedValues);
     48     return;
     49   }
     50
     51   for (var i = 0; i < collection.length; i++) {
     52     var inputValue = collection[i];
     53
     54     var callback = (function(position) {
     55
     56       return function(transformedValue) {
     57         transformedValues[position] = transformedValue;
     58
     59         if (--outstandingRequests == 0) {
     60           onComplete(transformedValues);
     61         };
     62       };
     63     });
     64
     65     doer(inputValue, callback(i));
     66   }
     67 };
     68
     69 /**
     70  * Implementation of Array#replaceAll
     71  * @private
     72  * @param array
     73  * @param newContents
     74  */
     75 pockets.collections.array.replaceAll = function(array, newContents) {
     76   array.splice.apply(array, [0, array.length].concat(newContents));
     77   return array;
     78 };
     79
     80 /**
     81  * Implementation of Array#remove
     82  * @private
     83  * @param array
     84  * @param item
     85  */
     86 pockets.collections.array.remove = function(array, item) {
     87   var itemIndex = array.indexOf(item);
     88   while(itemIndex != -1) {
     89     array.splice(itemIndex, 1);
     90     itemIndex = array.indexOf(item);
     91   }
     92 };