UNPKG

3 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3var HeadNode = /** @class */ (function () {
4 function HeadNode() {
5 // eslint-disable-next-line @typescript-eslint/no-use-before-define
6 this.next = new TailNode(this);
7 }
8 return HeadNode;
9}());
10exports.HeadNode = HeadNode;
11var TailNode = /** @class */ (function () {
12 function TailNode(head) {
13 this.previous = head;
14 }
15 return TailNode;
16}());
17exports.TailNode = TailNode;
18var LinkedListNode = /** @class */ (function () {
19 function LinkedListNode(item) {
20 this.next = null;
21 this.previous = null;
22 this.item = item;
23 }
24 LinkedListNode.prototype.detachSelf = function () {
25 if (!this.next && !this.previous) {
26 throw new Error('node is not attached');
27 }
28 if (this.next) {
29 this.next.previous = this.previous;
30 }
31 if (this.previous) {
32 this.previous.next = this.next;
33 }
34 this.next = null;
35 this.previous = null;
36 };
37 LinkedListNode.prototype.attachAfter = function (node) {
38 if (this.next || this.previous) {
39 throw new Error('Node is inserted elsewhere');
40 }
41 this.next = node.next;
42 this.previous = node;
43 if (node.next) {
44 node.next.previous = this;
45 }
46 node.next = this;
47 };
48 LinkedListNode.prototype.attachBefore = function (node) {
49 if (!node.previous) {
50 throw new Error('no previous node found.');
51 }
52 this.attachAfter(node.previous);
53 };
54 return LinkedListNode;
55}());
56exports.LinkedListNode = LinkedListNode;
57var LinkedList = /** @class */ (function () {
58 function LinkedList() {
59 this.head = new HeadNode();
60 this.tail = this.head.next;
61 }
62 LinkedList.prototype.add = function (item) {
63 var newNode = new LinkedListNode(item);
64 newNode.attachAfter(this.tail.previous);
65 return newNode;
66 };
67 LinkedList.prototype.getItems = function () {
68 var result = [];
69 this.forEach(function (item) {
70 result.push(item);
71 });
72 return result;
73 };
74 LinkedList.prototype.forEach = function (callback) {
75 var current = this.head.next;
76 while (current !== this.tail) {
77 // if item is not tail it is always a node
78 var item = current;
79 callback(item.item, item);
80 if (!item.next) {
81 throw new Error('badly attached item found.');
82 }
83 current = item.next;
84 }
85 };
86 LinkedList.prototype.hasItems = function () {
87 return this.head.next !== this.tail;
88 };
89 LinkedList.prototype.getLastItem = function () {
90 if (!this.hasItems()) {
91 throw new Error('no items in list.');
92 }
93 return this.head.next;
94 };
95 return LinkedList;
96}());
97exports.LinkedList = LinkedList;
98//# sourceMappingURL=LinkedList.js.map
\No newline at end of file