Deque.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. "use strict";
  2. const DoublyLinkedList = require("./DoublyLinkedList");
  3. const DequeIterator = require("./DequeIterator");
  4. /**
  5. * DoublyLinkedList backed double ended queue
  6. * implements just enough to keep the Pool
  7. */
  8. class Deque {
  9. constructor() {
  10. this._list = new DoublyLinkedList();
  11. }
  12. /**
  13. * removes and returns the first element from the queue
  14. * @return {any} [description]
  15. */
  16. shift() {
  17. if (this.length === 0) {
  18. return undefined;
  19. }
  20. const node = this._list.head;
  21. this._list.remove(node);
  22. return node.data;
  23. }
  24. /**
  25. * adds one elemts to the beginning of the queue
  26. * @param {any} element [description]
  27. * @return {any} [description]
  28. */
  29. unshift(element) {
  30. const node = DoublyLinkedList.createNode(element);
  31. this._list.insertBeginning(node);
  32. }
  33. /**
  34. * adds one to the end of the queue
  35. * @param {any} element [description]
  36. * @return {any} [description]
  37. */
  38. push(element) {
  39. const node = DoublyLinkedList.createNode(element);
  40. this._list.insertEnd(node);
  41. }
  42. /**
  43. * removes and returns the last element from the queue
  44. */
  45. pop() {
  46. if (this.length === 0) {
  47. return undefined;
  48. }
  49. const node = this._list.tail;
  50. this._list.remove(node);
  51. return node.data;
  52. }
  53. [Symbol.iterator]() {
  54. return new DequeIterator(this._list);
  55. }
  56. iterator() {
  57. return new DequeIterator(this._list);
  58. }
  59. reverseIterator() {
  60. return new DequeIterator(this._list, true);
  61. }
  62. /**
  63. * get a reference to the item at the head of the queue
  64. * @return {any} [description]
  65. */
  66. get head() {
  67. if (this.length === 0) {
  68. return undefined;
  69. }
  70. const node = this._list.head;
  71. return node.data;
  72. }
  73. /**
  74. * get a reference to the item at the tail of the queue
  75. * @return {any} [description]
  76. */
  77. get tail() {
  78. if (this.length === 0) {
  79. return undefined;
  80. }
  81. const node = this._list.tail;
  82. return node.data;
  83. }
  84. get length() {
  85. return this._list.length;
  86. }
  87. }
  88. module.exports = Deque;