DoublyLinkedList.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. // Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation
  6. // used for queues. This implementation assumes that the node provided by the user can be modified
  7. // to adjust the next and last properties. We implement only the minimal functionality
  8. // for queue support.
  9. class DLL {
  10. constructor() {
  11. this.head = this.tail = null;
  12. this.length = 0;
  13. }
  14. removeLink(node) {
  15. if (node.prev) node.prev.next = node.next;else this.head = node.next;
  16. if (node.next) node.next.prev = node.prev;else this.tail = node.prev;
  17. node.prev = node.next = null;
  18. this.length -= 1;
  19. return node;
  20. }
  21. empty() {
  22. while (this.head) this.shift();
  23. return this;
  24. }
  25. insertAfter(node, newNode) {
  26. newNode.prev = node;
  27. newNode.next = node.next;
  28. if (node.next) node.next.prev = newNode;else this.tail = newNode;
  29. node.next = newNode;
  30. this.length += 1;
  31. }
  32. insertBefore(node, newNode) {
  33. newNode.prev = node.prev;
  34. newNode.next = node;
  35. if (node.prev) node.prev.next = newNode;else this.head = newNode;
  36. node.prev = newNode;
  37. this.length += 1;
  38. }
  39. unshift(node) {
  40. if (this.head) this.insertBefore(this.head, node);else setInitial(this, node);
  41. }
  42. push(node) {
  43. if (this.tail) this.insertAfter(this.tail, node);else setInitial(this, node);
  44. }
  45. shift() {
  46. return this.head && this.removeLink(this.head);
  47. }
  48. pop() {
  49. return this.tail && this.removeLink(this.tail);
  50. }
  51. toArray() {
  52. return [...this];
  53. }
  54. *[Symbol.iterator]() {
  55. var cur = this.head;
  56. while (cur) {
  57. yield cur.data;
  58. cur = cur.next;
  59. }
  60. }
  61. remove(testFn) {
  62. var curr = this.head;
  63. while (curr) {
  64. var { next } = curr;
  65. if (testFn(curr)) {
  66. this.removeLink(curr);
  67. }
  68. curr = next;
  69. }
  70. return this;
  71. }
  72. }
  73. exports.default = DLL;
  74. function setInitial(dll, node) {
  75. dll.length = 1;
  76. dll.head = dll.tail = node;
  77. }
  78. module.exports = exports["default"];