runsQueue.js 1.7 KB

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