serialOrdered.js 1.7 KB

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