runsQueue.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. var Q = require('q');
  2. var debug = require('debug')('ylt:runsQueue');
  3. function RunsQueue() {
  4. 'use strict';
  5. var queue = [];
  6. this.push = function(runId) {
  7. var deferred = Q.defer();
  8. var startingPosition = queue.length;
  9. debug('Adding run %s to the queue, position is %d', runId, startingPosition);
  10. if (startingPosition === 0) {
  11. // The queue is empty, let's run immediatly
  12. queue.push({
  13. runId: runId
  14. });
  15. deferred.resolve();
  16. } else {
  17. queue.push({
  18. runId: runId,
  19. positionChangedCallback: function(position) {
  20. deferred.notify(position);
  21. },
  22. itIsTimeCallback: function() {
  23. deferred.resolve();
  24. }
  25. });
  26. }
  27. var promise = deferred.promise;
  28. promise.startingPosition = startingPosition;
  29. return promise;
  30. };
  31. this.getPosition = function(runId) {
  32. // Position 0 means it's a work in progress (a run is removed AFTER it is finished, not before)
  33. var position = -1;
  34. queue.some(function(run, index) {
  35. if (run.runId === runId) {
  36. position = index;
  37. return true;
  38. }
  39. return false;
  40. });
  41. return position;
  42. };
  43. this.remove = function(runId) {
  44. var position = this.getPosition(runId);
  45. if (position >= 0) {
  46. queue.splice(position, 1);
  47. }
  48. // Update other runs' positions
  49. queue.forEach(function(run, index) {
  50. if (index === 0 && run.itIsTimeCallback) {
  51. run.itIsTimeCallback();
  52. } else if (index > 0 && run.positionChangedCallback) {
  53. run.positionChangedCallback(index);
  54. }
  55. });
  56. };
  57. this.length = function() {
  58. return queue.length;
  59. };
  60. }
  61. module.exports = RunsQueue;