runsQueue.js 1.8 KB

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