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