UNPKG

1.8 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.default = DLL;
7// Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation
8// used for queues. This implementation assumes that the node provided by the user can be modified
9// to adjust the next and last properties. We implement only the minimal functionality
10// for queue support.
11function DLL() {
12 this.head = this.tail = null;
13 this.length = 0;
14}
15
16function setInitial(dll, node) {
17 dll.length = 1;
18 dll.head = dll.tail = node;
19}
20
21DLL.prototype.removeLink = function (node) {
22 if (node.prev) node.prev.next = node.next;else this.head = node.next;
23 if (node.next) node.next.prev = node.prev;else this.tail = node.prev;
24
25 node.prev = node.next = null;
26 this.length -= 1;
27 return node;
28};
29
30DLL.prototype.empty = DLL;
31
32DLL.prototype.insertAfter = function (node, newNode) {
33 newNode.prev = node;
34 newNode.next = node.next;
35 if (node.next) node.next.prev = newNode;else this.tail = newNode;
36 node.next = newNode;
37 this.length += 1;
38};
39
40DLL.prototype.insertBefore = function (node, newNode) {
41 newNode.prev = node.prev;
42 newNode.next = node;
43 if (node.prev) node.prev.next = newNode;else this.head = newNode;
44 node.prev = newNode;
45 this.length += 1;
46};
47
48DLL.prototype.unshift = function (node) {
49 if (this.head) this.insertBefore(this.head, node);else setInitial(this, node);
50};
51
52DLL.prototype.push = function (node) {
53 if (this.tail) this.insertAfter(this.tail, node);else setInitial(this, node);
54};
55
56DLL.prototype.shift = function () {
57 return this.head && this.removeLink(this.head);
58};
59
60DLL.prototype.pop = function () {
61 return this.tail && this.removeLink(this.tail);
62};
63module.exports = exports['default'];
\No newline at end of file