1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | class HeadNode {
|
4 | constructor() {
|
5 | this.next = new TailNode(this);
|
6 | }
|
7 | }
|
8 | exports.HeadNode = HeadNode;
|
9 |
|
10 | class TailNode {
|
11 | constructor(head) {
|
12 | this.previous = head;
|
13 | }
|
14 | }
|
15 | exports.TailNode = TailNode;
|
16 |
|
17 | class 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 | }
|
54 | exports.LinkedListNode = LinkedListNode;
|
55 |
|
56 | class 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 |
|
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 | }
|
95 | exports.LinkedList = LinkedList;
|
96 |
|
\ | No newline at end of file |