2
0

queue.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import { __awaiter } from "tslib";
  2. class Queue {
  3. constructor() {
  4. this.status = "waiting";
  5. }
  6. append(item, autoRun = true) {
  7. const node = new Node(item);
  8. if (!this.current || !this.end) {
  9. this.current = this.end = node;
  10. }
  11. else {
  12. this.end.setNext(node);
  13. this.end = node;
  14. }
  15. if (autoRun) {
  16. this.startRun();
  17. }
  18. }
  19. startRun() {
  20. if (this.status === "waiting") {
  21. this.run();
  22. }
  23. }
  24. run() {
  25. return __awaiter(this, void 0, void 0, function* () {
  26. if (this.current) {
  27. this.status = "running";
  28. const current = this.current;
  29. const self = current.getSelf();
  30. this.current = this.current.getNext();
  31. const res = yield self.run();
  32. current.destroy();
  33. if (res === false) {
  34. this.status = "waiting";
  35. }
  36. else {
  37. this.run();
  38. }
  39. }
  40. else {
  41. this.end = undefined;
  42. this.status = "waiting";
  43. }
  44. });
  45. }
  46. }
  47. class Node {
  48. constructor(self) {
  49. this.self = self;
  50. }
  51. getSelf() {
  52. return this.self;
  53. }
  54. setPrev(prev) {
  55. this.prev = prev;
  56. if (prev) {
  57. prev.next = this;
  58. }
  59. }
  60. setNext(next) {
  61. this.next = next;
  62. if (next) {
  63. next.prev = this;
  64. }
  65. }
  66. getPrev() {
  67. return this.prev;
  68. }
  69. getNext() {
  70. return this.next;
  71. }
  72. destroy() {
  73. if (this.prev) {
  74. this.prev.setNext(undefined);
  75. }
  76. if (this.next) {
  77. this.next.setPrev(undefined);
  78. }
  79. this.prev = undefined;
  80. this.next = undefined;
  81. this.self = undefined;
  82. }
  83. }
  84. export { Queue };