Guest User

Untitled

a guest
May 22nd, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. class AsyncQueue<T> {
  2. waitingEnqueue = new Array<() => void>()
  3. waitingDequeue = new Array<() => void>()
  4. enqueuePointer = 0
  5. dequeuePointer = 0
  6. queue = Array<T>()
  7. maxSize = 1
  8.  
  9. async enqueue(x: T) {
  10. if ((this.queue.length + 1) > this.maxSize || this.waitingDequeue.length > 0) {
  11. this.dequeuePointer += 1
  12. await new Promise(r => this.waitingDequeue.unshift(r))
  13. this.waitingDequeue.pop()
  14. }
  15.  
  16. this.queue.unshift(x)
  17.  
  18. if (this.enqueuePointer > 0) {
  19. this.waitingEnqueue[this.enqueuePointer-1]()
  20. this.enqueuePointer -= 1
  21. }
  22. }
  23.  
  24. async dequeue() {
  25. if (this.queue.length == 0 || this.waitingEnqueue.length > 0) {
  26. this.enqueuePointer += 1
  27. await new Promise(r => this.waitingEnqueue.unshift(r))
  28. this.waitingEnqueue.pop()
  29. }
  30.  
  31. if (this.dequeuePointer > 0) {
  32. this.waitingDequeue[this.dequeuePointer - 1]()
  33. this.dequeuePointer -= 1
  34. }
  35.  
  36. return this.queue.pop()!
  37. }
  38. }
Add Comment
Please, Sign In to add comment