buddy

node MVC discord bot
Log | Files | Refs | README

serialOrdered.js (1751B)


      1 var iterate    = require('./lib/iterate.js')
      2   , initState  = require('./lib/state.js')
      3   , terminator = require('./lib/terminator.js')
      4   ;
      5 
      6 // Public API
      7 module.exports = serialOrdered;
      8 // sorting helpers
      9 module.exports.ascending  = ascending;
     10 module.exports.descending = descending;
     11 
     12 /**
     13  * Runs iterator over provided sorted array elements in series
     14  *
     15  * @param   {array|object} list - array or object (named list) to iterate over
     16  * @param   {function} iterator - iterator to run
     17  * @param   {function} sortMethod - custom sort function
     18  * @param   {function} callback - invoked when all elements processed
     19  * @returns {function} - jobs terminator
     20  */
     21 function serialOrdered(list, iterator, sortMethod, callback)
     22 {
     23   var state = initState(list, sortMethod);
     24 
     25   iterate(list, iterator, state, function iteratorHandler(error, result)
     26   {
     27     if (error)
     28     {
     29       callback(error, result);
     30       return;
     31     }
     32 
     33     state.index++;
     34 
     35     // are we there yet?
     36     if (state.index < (state['keyedList'] || list).length)
     37     {
     38       iterate(list, iterator, state, iteratorHandler);
     39       return;
     40     }
     41 
     42     // done here
     43     callback(null, state.results);
     44   });
     45 
     46   return terminator.bind(state, callback);
     47 }
     48 
     49 /*
     50  * -- Sort methods
     51  */
     52 
     53 /**
     54  * sort helper to sort array elements in ascending order
     55  *
     56  * @param   {mixed} a - an item to compare
     57  * @param   {mixed} b - an item to compare
     58  * @returns {number} - comparison result
     59  */
     60 function ascending(a, b)
     61 {
     62   return a < b ? -1 : a > b ? 1 : 0;
     63 }
     64 
     65 /**
     66  * sort helper to sort array elements in descending order
     67  *
     68  * @param   {mixed} a - an item to compare
     69  * @param   {mixed} b - an item to compare
     70  * @returns {number} - comparison result
     71  */
     72 function descending(a, b)
     73 {
     74   return -1 * ascending(a, b);
     75 }