1 /*
  2  Based on code originating from the 'async' module - author license included here below:
  3 
  4  Copyright (c) 2010 Caolan McMahon
  5 
  6  Permission is hereby granted, free of charge, to any person obtaining a copy
  7  of this software and associated documentation files (the "Software"), to deal
  8  in the Software without restriction, including without limitation the rights
  9  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 10  copies of the Software, and to permit persons to whom the Software is
 11  furnished to do so, subject to the following conditions:
 12 
 13  The above copyright notice and this permission notice shall be included in
 14  all copies or substantial portions of the Software.
 15 
 16  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 17  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 18  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 19  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 20  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 21  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 22  THE SOFTWARE.
 23  */
 24 
 25 exports.enqueue = function _enqueue(tasks, callback) {
 26   callback = callback || function () {
 27   };
 28   if (!tasks.length) {
 29     return callback();
 30   }
 31 
 32   var wrapIterator = function (iterator) {
 33     return function (err) {
 34       if (err) {
 35         callback(err);
 36         callback = function () {
 37         };
 38       } else {
 39         var args = Array.prototype.slice.call(arguments, 1);
 40         var next = iterator.next();
 41         if (next) {
 42           args.push(wrapIterator(next));
 43         } else {
 44           args.push(callback);
 45         }
 46         process.nextTick(function () {
 47           iterator.apply(null, args);
 48         });
 49       }
 50     };
 51   };
 52   wrapIterator(iterator(tasks))();
 53 };
 54 
 55 exports.while = function _while(test, iterator, callback) {
 56   if (test()) {
 57     iterator(function (err) {
 58       if (err) {
 59         return callback(err);
 60       }
 61       _while(test, iterator, callback);
 62     });
 63   } else {
 64     callback();
 65   }
 66 };
 67 
 68 function iterator(tasks) {
 69   var makeCallback = function (index) {
 70     var fn = function () {
 71       if (tasks.length) {
 72         tasks[index].apply(null, arguments);
 73       }
 74       return fn.next();
 75     };
 76     fn.next = function () {
 77       return (index < tasks.length - 1) ? makeCallback(index + 1) : null;
 78     };
 79     return fn;
 80   };
 81   return makeCallback(0);
 82 }
 83 
 84