UNPKG

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