Advertisement
Guest User

Untitled

a guest
Jun 26th, 2019
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 KB | None | 0 0
  1. import EventEmitter from 'events';
  2.  
  3. class Node {
  4. constructor(data) {
  5. this._data = data;
  6. this._next = null;
  7. }
  8.  
  9. get data() {
  10. return this._data;
  11. }
  12.  
  13. get next() {
  14. return this._next;
  15. }
  16.  
  17. set next(val) {
  18. this._next = val;
  19. }
  20. }
  21.  
  22. class Queue extends EventEmitter {
  23. constructor(initDatas = [], maxSize = 0) {
  24. super();
  25. EventEmitter.call(this);
  26.  
  27. this._front = null;
  28. this._tail = null;
  29. this._size = 0;
  30. this._maxSize = maxSize;
  31.  
  32. for (const d of initDatas) {
  33. this.enque(d);
  34. }
  35. }
  36.  
  37. push(data) {
  38. const node = new Node(data);
  39.  
  40. if (!this._tail) {
  41. this._front = node;
  42. this._tail = node;
  43. } else {
  44. this._tail.next = node;
  45. this._tail = node;
  46. }
  47.  
  48. this._size += 1;
  49.  
  50. if (this._maxSize > 0 && this._size > this._maxSize) {
  51. this.pop();
  52. }
  53.  
  54. this.emit('pushed');
  55. return this._size;
  56. }
  57.  
  58. pop() {
  59. if (!this._front || this._size === 0) return null;
  60.  
  61. const node = this._front;
  62. this._front = this._front.next;
  63. if (!this._front) {
  64. this._tail = null;
  65. }
  66. this._size = Math.max(0, this._size - 1);
  67. return node.data;
  68. }
  69.  
  70. clear() {
  71. while (this.size() > 0) {
  72. this.pop();
  73. }
  74. }
  75.  
  76. size() {
  77. return Math.max(0, this._size);
  78. }
  79. }
  80.  
  81. export default Queue;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement